How can I efficiently filter an array of objects by a specific value that could be located in any property?
Consider the following object:
var x = [
{
name: "one",
swp: "two"
},
{
name: "two",
swp: "three"
},
{
name: "aa",
swp: "bb"
}
];
Using Array.prototype.filter
, I could do:
x.filter(function(y){ return y.name == "two"; });
However, this would only return one object out of the two that have "two" as a value in any property.
On the other hand, the following function:
function findValue( value ) {
var y = [];
for (obj in x) {
for (val in x[obj]) {
if (x[obj][val].match( value )) {
y.push(x[obj]);
}
}
}
return y;
}
accomplishes the task, but it is a brute force method. Is there a more efficient way to achieve the same result?