最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How do I get an item from a JavaScript object? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Aug 19, 2010 at 1:19 Daniel Vassallo 344k72 gold badges512 silver badges446 bronze badges asked Aug 17, 2010 at 22:39 colemandecolemande 3921 gold badge5 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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)

  1. 暂无评论