如何从 JavaScript 对象中获取项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3507542/
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-10-25 01:22:00  来源:igfitidea点击:

How do I get an item from a JavaScript object?

javascriptjqueryjson

提问by colemande

How do I get an item from a JavaScript object:

如何从 JavaScript 对象获取项目:

var items = [
  {
    ITEM:1,
    AMOUNT:10
  },
  {
    ITEM:2,
    AMOUNT:20
  }
];

I want to be able to do something like this:

我希望能够做这样的事情:

$(items).filter(ITEM == 1).AMOUNT;

... which would return 10.

...这将返回10

采纳答案by casablanca

You can use the Array filtermethod, which returns a new array containing all matching elements. (there could be more than one matching item)

您可以使用 Arrayfilter方法,该方法返回一个包含所有匹配元素的新数组。(可能有多个匹配项)

var results = items.filter(function(obj) { return obj.ITEM == 1; });
for (var i = 0; i < results.length; i++)
  alert(results[i].AMOUNT);

Note that IE6 (I'm not sure about newer versions) doesn't support the filtermethod. You could always define it yourself if it doesn't exist:

请注意,IE6(我不确定更新版本)不支持该filter方法。如果它不存在,你总是可以自己定义它:

if (typeof Array.prototype.filter == 'undefined')
  Array.prototype.filter = function(callback) {
    var result = [];
    for (var i = 0; i < this.length; i++)
      if (callback(this[i]))
        result.push(this[i]);
    return result;
  }

回答by Daniel Vassallo

Your are creating an array of objects. If the items are inserted in order, you could use:

您正在创建一个对象数组。如果项目按顺序插入,您可以使用:

items[0].AMOUNT;   // return the amount of the first item in the array

However, (using plain JavaScript) you may probably prefer to exploit the hashtable nature of JavaScript objects, and use something like this:

但是,(使用纯 JavaScript)您可能更喜欢利用 JavaScript 对象的哈希表特性,并使用以下内容:

var items = {
    item1: {
       amount: 10
    },
    item2: {
       amount: 20
    }
};

Then you will be able to use either the subscript notation:

然后您将能够使用下标符号:

items['item1'].amount;

... or the dot notation:

...或点符号:

items.item1.amount;


@casablanca's solutionis a valid alternative, but note that the filter()method runs in O(n)since the supplied selector is tested against each element of the array. On the other hand, an item from a hashtable can be found in O(1)(constant time).

@casablanca 的解决方案是一个有效的替代方案,但请注意该filter()方法在O(n) 中运行, 因为提供的选择器针对数组的每个元素进行测试。另一方面,可以在O(1)(恒定时间)中找到哈希表中的项目。