开发者

How do I get an item from a JavaScript object?

开发者 https://www.devze.com 2023-01-11 20:06 出处:网络
开发者_如何转开发How do I get an item from a JavaScript object: var items = [ { ITEM:1, AMOUNT:10

开发者_如何转开发How do I get an item from a JavaScript object:

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.


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:

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 solution is 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).


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

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 filter method. You could always define it yourself if it doesn't exist:

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;
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消