1

I have an array of objects, each object contains n key/value pairs. I need to return an array of the objects which has a value matching x.

Using Underscore.js I could use _.findWhere however I don't know what key the value will be under.

I could obviously loop the array, fetch all of the keys in each object, then run _.findWhere on each key and check if the value is there, but it doesn't seem like a good way of doing this.

2
  • Please tell me why this is off-topic? I'm trying to find a value within an object in the best way possible. Commented Jan 29, 2014 at 10:04
  • 1
    Actually, the best (i.e performant) way is Object.keys() + for-loop. Commented Jan 29, 2014 at 10:15

3 Answers 3

1

I could obviously loop the array, fetch all of the keys in each object...

Yes.

Write a function that accepts an array and a value to look for in its elements members, loop over the array, loop over the keys of the current element, and push the objects containing a member with a matching value to an array and return it after the iteration.

function findValues (arr,val) {
    var result = [];
    for (var i=0,current;i<arr.length;i++) {
        current = arr [i];
        for (var key in current) {
            if (current [key] === val) {
               result.push (current);
            }
        }
    }
    return result
}

Here is an example output

findValues (
   [{
     a:1,
     b:2,
     c:3
   },{
     a:1,
     b:2,
   },{
     a:1,
     b:2,
   },{
     a:1,
     b:2,
     c:3,
     d:4
   },{
     a:1,
     b:2,
   }],
   3
) //[{"a":1,"b":2,"c":3},{"a":1,"b":2,"c":3,"d":4}]
Sign up to request clarification or add additional context in comments.

Comments

1

I think, that the best way is:

Object.prototype.someProperty = function(fn){
    for (var key in this) {
        if (fn(key, this[key])) return true;
    }
    return false;
};
Array.prototype.filter = function(fn) {
    var a = [],
        l = this.length;
    for (var i = 0; i < l; i++) {
        if (fn(this[i])) a.push(this[i]);
    }
    return a;
};

// test
var a = [
    {a: 6, b: 8}
    ,{f: 7, c: 6, d: 67}
    ,{d: 4, c: 5, g: 8}
];
var b = a.filter(function(item){
    return item.someProperty(function(k, v){
        return v == 8;
    });
});
console.dir(b);

Comments

1

This should do the trick:

var filteredList = _.filter(values, function(value){
     return _.contains(value, 3); 
});

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.