sparecycle sparecycle - 1 month ago 11
Javascript Question

Having trouble extracting value from Javascript object's multidimensonal array

I'm attempting to use Javascript objects to work with some data. Here is the object itself (parsed from JSON) which is defined as accounts:

{
startIndex: 0,
pageSize: 20,
pageCount: 1,
totalCount: 1,
items: [
{
id: 123456,
emailAddress: 'test@test.com',
userName: 'test@test.com',
firstName: 'John',
lastName: 'Hancock',
customerSet: 'default',
commerceSummary: [
Object
],
contacts: [
Object
],
userId: '92834439c29389fj292',
notes: [

],
attributes: [
Object
],
segments: [
Object
],
taxExempt: false,
externalId: '2100010368',
isAnonymous: false,
auditInfo: [
Object
],
isLocked: false,
isActive: true,
hasExternalPassword: false,
customerSinceDate: 2016-06-23T18: 26: 46.000Z
}
]
}


While I can retrieve accounts.items without issue, I'm having some trouble retrieving individual values such as id or emailAddress from the item itself. Doing accounts.items[id] or accounts.items[emailAddress] does not work but I believe it's due to the fact that items can be more than 1 so I should be specifying the "first result" for items from that list. If that is the case, how do I retrieve the emailAddress or id for the first items array? The desired result from the above JSON object should be "123456" if id and "test@test.com" if email. Thanks in advance.

Answer

Your items is an array. You have to fetch data from it by indexes (like items[0]). If you are looking for an item, with their properties, use Array.find method.

The find method executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element. Otherwise, find returns undefined. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

var accounts = {
  startIndex: 0,
  pageSize: 20,
  pageCount: 1,
  totalCount: 1,
  items: [
    {
      id: 123456,
      emailAddress: 'test@test.com',
      userName: 'test@test.com',
      firstName: 'John',
      lastName: 'Hancock',
      customerSet: 'default'
    }
  ]
};

var sampleAccount = accounts.items.find(function (item) {
  return item.id == 123456;
});

if (sampleAccount) {
  console.log(sampleAccount.emailAddress);
}

Comments