根据值过滤对象数组 [英] Filtering array of objects based on value
问题描述
是否有一种方法可以通过可以在任何属性中使用的特定值来过滤对象数组?
Is there a way to filter an array of objects by a particular value that could be in any property?
假设我有这个对象:
var x = [
{
name: "one",
swp: "two"
},
{
name: "two",
swp: "three"
},
{
name: "aa",
swp: "bb"
}
];
我可能会用Array.prototype.filter
x.filter(function(y){ return y.name == "two"; });
但是,这将仅返回两个对象中任何一个属性的值为两个"的对象中的一个.
However this would return only one out of the two objects that have "two" as a value in any of their properties.
而
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;
}
可以胜任,但这是蛮力的方法. 有没有更好的方法来达到相同的结果?
does the job, but is a brute force approach. Is there a better way to achieve the same result?
推荐答案
var arrOfObj = []; // objects you're sifting
var prop = 'whatever';
var matches = arrOfObj.filter(obj => Object.keys(obj).some(k => obj[k] === prop));
您需要 Array.prototype.filter
的组合和 Array.prototype.some
如果数组中的任何元素与条件匹配,则返回一个布尔值,一旦找到匹配项,它也将停止迭代数组(在这种情况下,每个对象的键).如果您需要跨浏览器支持(由于某种原因未使用babel),则上述ES 5版本为
You want a combination of Array.prototype.filter
and Array.prototype.some
which returns a boolean if any of the elements of the array match the condition, it also stops iterating the array (in this case the keys of each object) as soon as it finds a match. If you need cross-browser support (and for some reason aren't using babel) the ES 5 version of the above is
var arrOfObj = []; // objects you're sifting
var prop = 'whatever';
var matches = arrOfObj.filter(function(obj) {
return Object.keys(obj).some(function(k) {
return obj[k] === prop;
});
});
这篇关于根据值过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!