Question

Let say I have a 5 objects like so in an array:

var myObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 1, b: 6}, {a: 3, b: 8}, {a: 1, b: 9}];

How can I iterate though this myObjects and get objects having similar value a = 1. eg. {a: 1, b: 2},{a: 1, b: 6},{a: 1, b: 9} as a result?

Was it helpful?

Solution

Use Array.prototype.filter:

var result = myObjects.filter(function(e) {
    return e.a === 1;
});

MDN provides a polyfill for old browsers which don't support this method.

If you want to group objects based on property a, then you may use the following approach:

var result = {};

for (var i = 0, len = myObjects.length; i < len; i++) {
    var obj = myObjects[i];

    if (result[obj.a] === undefined) {
        result[obj.a] = [];
    }

    result[obj.a].push(obj);
}

console.log(result);

OTHER TIPS

Extending on @VisioN's answer: You can use a factory function that itself returns a function to filter by:

function filterAByValue(value) {
  return function(item) {
    return item.a === value;
  };
}

var result = myObjects.filter(filterAByValue(1));

Or even make the property variable:

function filterPropertyByValue(property, value) {
  return function(item) {
    return item[property] === value;
  };
}

var result = myObjects.filter(filterPropertyByValue("a", 1));

Try this

var index[];
for(i=0;i<obj.lenght;i++)
{
    if(obj[i].a==1)
    {
       index.push(i);
       //you even can push obj[i] to some other array and use it
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top