我有一个对象数组,每个对象包含 n
键/值对。我需要返回一个对象数组,其值与 x
匹配。
使用 Underscore.js 我可以使用 _.findWhere
但是我不知道该值将位于哪个键下。
我显然可以循环数组,获取每个对象中的所有键,然后在每个键上运行 _.findWhere
并检查值是否存在,但它看起来不像这样做的好方法。
最佳答案
I could obviously loop the array, fetch all of the keys in each object...
是的。
编写一个函数,接受一个数组和一个值以在其元素成员中查找,循环遍历数组,循环遍历当前元素的键,并将包含具有匹配值的成员的对象推送到数组中,并且迭代后返回。
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
}
这是一个 example输出
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}]
关于javascript - 在对象数组中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21427180/