I have an object that contains an array list of objects. I'd like to get the value of an object within the array list.
example
var data = {
items1: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }],
items2: [{ id: 3, name: 'foo' }, { id: 4, name: 'bar' }]
};
I'm trying to access the name of id:1 in array list items1.
I thought it would be something like
data['items1']['id'].name
but I think I'm missing something. Anybody know what I might be doing wrong
I have an object that contains an array list of objects. I'd like to get the value of an object within the array list.
example
var data = {
items1: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }],
items2: [{ id: 3, name: 'foo' }, { id: 4, name: 'bar' }]
};
I'm trying to access the name of id:1 in array list items1.
I thought it would be something like
data['items1']['id'].name
but I think I'm missing something. Anybody know what I might be doing wrong
Share Improve this question edited Sep 22, 2013 at 6:17 Kelsadita 1,0388 silver badges22 bronze badges asked Sep 22, 2013 at 5:57 Code JunkieCode Junkie 7,78827 gold badges86 silver badges146 bronze badges 3- For starters, that appears to be invalid json, given you don't have a ma after the first item. – Daedalus Commented Sep 22, 2013 at 6:00
- Feel free to correct the issue you see, I just quickly modified the post from another example on the web to try and demonstrate what I'm trying to do. – Code Junkie Commented Sep 22, 2013 at 6:02
- Not going to. One never modifies the code in the OP's question, as that changes the meaning. If the code is faulty, or they misposted, it is their job to fix/correct it. – Daedalus Commented Sep 22, 2013 at 6:04
4 Answers
Reset to default 5This is an object with 2 keys (items1
and items2
), both of which are arrays. Within each array are elements which are objects, each containing 2 keys (id
and name
).
To get the id
of the first element of the items1
array you would do:
data.items1[0].id
which would return 1
.
If you wanted to search for the object with a name of 'bar' in items2
you could do something like:
function find(item, name) {
//no such array
if(!data[item])
return;
//search array for key
var items = data[item];
for(var i = 0; i < items.length; ++i) {
//if the name is what we are looking for return it
if(items[i].name === name)
return items[i];
}
}
var obj = find('items2', 'bar');
obj.id; //4
obj.name; //'bar'
I highly suggest reading about JavaScript Objects and Arrays.
You can only access array items by their numeric index. For example:
// The first item in the array
data['items1'][0].name
// The second
data['items1'][1].name
If you want to lookup by id, you can make a little function to do that for you:
function getItemById(anArray, id) {
for (var i = 0; i < anArray.length; i += 1) {
if (anArray[i].id === id) {
return anArray[i];
}
}
}
var theName = getItemById(data['items1'], 1).name;
As items1 is array, you should write:
data.items1[0].name
Try this data['items1'][0].name