How to get an element from a JavaScript object?

How to get an element from a JavaScript object:

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

I want to do something like this:

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

... which will return 10.

+3
source share
2 answers

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

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

Please note that IE6 (I'm not sure about newer versions) does not support the method filter. You can always define it yourself if it does not 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;
  }
+3
source

An array of objects is created. If the elements are inserted in order, you can use:

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

, JavaScript, , , - JavaScript - :

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

:

items['item1'].amount;

... :

items.item1.amount;

@casablanca solution , , filter() O (n), . , - O (1) ( ).

+5

Source: https://habr.com/ru/post/1760203/


All Articles