Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an item from a JavaScript object?

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.

like image 235
colemande Avatar asked Dec 28 '22 08:12

colemande


2 Answers

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

like image 185
Daniel Vassallo Avatar answered Dec 31 '22 01:12

Daniel Vassallo


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;
  }
like image 23
casablanca Avatar answered Dec 31 '22 01:12

casablanca