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}]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments