1

我有一个包含对象数组列表的对象。我想在数组列表中获取一个对象的值。

例子

var data = { 
             items1: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }], 
             items2: [{ id: 3, name: 'foo' }, { id: 4, name: 'bar' }] 
           };

我正在尝试访问数组列表 items1 中 id:1 的名称。

我以为会是这样的

data['items1']['id'].name 

但我想我错过了一些东西。任何人都知道我可能做错了什么

4

4 回答 4

5

This 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.

于 2013-09-22T06:04:54.253 回答
3

您只能通过数字索引访问数组项。例如:

// The first item in the array
data['items1'][0].name
// The second
data['items1'][1].name

如果您想通过 id 查找,您可以创建一个小函数来为您执行此操作:

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;
于 2013-09-22T06:10:46.067 回答
2

由于 items1 是数组,你应该写:

data.items1[0].name
于 2013-09-22T06:03:55.067 回答
1

尝试这个data['items1'][0].name

于 2013-09-22T06:01:41.803 回答