jQuery 按数组列表中的名称访问对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18940847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:49:23  来源:igfitidea点击:

Access object by name in array list

javascriptjquery

提问by Code Junkie

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.

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

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

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

回答by Chad

This is an object with 2 keys (items1and items2), both of which are arrays. Within each array are elements which are objects, each containing 2 keys (idand name).

这是一个具有 2 个键 (items1items2)的对象,它们都是数组。每个数组中都有作为对象的元素,每个元素包含 2 个键(idname)。

To get the idof the first element of the items1array you would do:

要获取数组id的第一个元素的 ,items1您将执行以下操作:

data.items1[0].id

which would return 1.

这将返回1

If you wanted to search for the object with a name of 'bar' in items2you could do something like:

如果您想搜索名称为“bar”的对象,items2您可以执行以下操作:

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 Objectsand Arrays.

我强烈建议阅读JavaScript Objectsand Arrays

回答by Hymanson

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:

如果您想通过 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;

回答by jancha

As items1 is array, you should write:

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

data.items1[0].name

回答by Kelsadita

Try this data['items1'][0].name

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