0

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?

3
  • If you don't know the value of a to search for then provide an example of the result you expect Commented Apr 24, 2014 at 11:06
  • i want to get {a: 1, b: 2},{a: 1, b: 6},{a: 1, b: 9} as a result array of objects because in these objects a is equal to 1 and same is true for any other values Commented Apr 24, 2014 at 11:09
  • But you said you don't know the value of a... so what is the rule to filter value = 1? How should the code know to remove a = 3? they won't be removed by magic, you need to define your rules. Why shouldn't the result be {a: 3, b: 4}, {a: 3, b: 8} for example? Commented Apr 24, 2014 at 11:13

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for reply but i have tried this, but in my case I don't know the value of 'a', i have just given that for clearity
@BijayRai Then the solution will be a bit more advanced. Please see the updated answer.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.