문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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

This should do the trick:

var filteredList = _.filter(values, function(value){
     return _.contains(value, 3); 
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top