Javascript 返回对象数组的所有匹配元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26844260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return all matching elements of an array of objects?
提问by Moritz Schmitz v. Hülst
I have an array that consists of objects with two properties.
我有一个由具有两个属性的对象组成的数组。
One property "value" is a number between 1 and 6. The other property "id" is a number between 1 and 200.
一个属性“value”是 1 到 6 之间的数字。另一个属性“id”是 1 到 200 之间的数字。
How can I return the "id" property of all objects with "value" = 1 and write them to a new array?
如何返回“value”= 1 的所有对象的“id”属性并将它们写入新数组?
回答by jAndy
You should invoke the Array.prototype.filterfunction there.
您应该在Array.prototype.filter那里调用该函数。
var filteredArray = YourArray.filter(function( obj ) {
return obj.value === 1;
});
.filter()requires you to return the desired condition. It will create a new array, based on the filtered results. If you further want to operate on that filtered Array, you could invoke more methods, like in your instance .map()
.filter()要求您返回所需的条件。它将根据过滤结果创建一个新数组。如果您还想对该过滤器进行操作Array,则可以调用更多方法,例如在您的实例中.map()
var filteredArray = YourArray.filter(function( obj ) {
return obj.value === 1;
}).map(function( obj ) {
return obj.id;
});
console.log( filteredArrays ); // a list of ids
... and somewhere in the near future, we can eventually use the Arrow functionsof ES6, which makes this code even more beauty:
...在不久的将来,我们最终可以使用ES6的Arrow 函数,这使得这段代码更加美观:
var filteredArray = YourArray.filter( obj => obj.value === 1 ).map( obj => obj.id );
回答by Michael Freund
Pure JS.... no filter/map functions, that are not available for IE < 9
纯 JS .... 没有过滤器/映射功能,不适用于 IE < 9
var array = [
{id:10, value:2}, {id:11, value:1}, {id:12, value:3}, {id:13, value:1}
],
result = [];
for(key in array) { if (array[key].value == 1) result.push(array[key].id); }
回答by Michael Freund
The good news is, it's easy, just write
好消息是,这很容易,只要写
[ for (obj of array) if (obj.value === 1) obj.id ]
The bad news is, it will some time before you can depend on all browsers to do this. It's from a new version of the language called "ES6". But you can try it right now in Firefox!!
坏消息是,你需要一段时间才能依赖所有浏览器来做到这一点。它来自名为“ES6”的新版本语言。但是您现在可以在 Firefox 中试用它!!
回答by Kuba Jagoda
You can use a combination of Array.prototype.filterand Array.prototype.map.
您可以使用的组合Array.prototype.filter和Array.prototype.map。
First, filter only values with valueequal to 1.
首先,仅过滤value等于 的值1。
arr.filter(function (obj) {
return obj.value === 1;
});
Then, you map existing collection to a new array, consisting only of idproperties stored in filtered array. So the final code:
然后,您将现有集合映射到一个新数组,该数组仅包含id存储在过滤数组中的属性。所以最后的代码:
var newArr = arr.filter(function (obj) {
return obj.value === 1;
}).map(function (obj) {
return obj.id;
});

