同时映射和过滤数组 [英] Map and filter an array at the same time
本文介绍了同时映射和过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组,我想迭代生成一个新的过滤数组。但是,我还需要根据参数从新数组中过滤掉一些对象。我正在尝试这个:
I have an array of objects that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I'm trying this:
function renderOptions(options) {
return options.map(function (option) {
if (!option.assigned) {
return (someNewObject);
}
});
}
这是一个好方法吗?有更好的方法吗?我愿意使用任何库,例如lodash。
Is that a good approach? Is there a better method? I'm open to use any library such as lodash.
推荐答案
你应该使用 Array.reduce
为此。
var options = [
{ name: 'One', assigned: true },
{ name: 'Two', assigned: false },
{ name: 'Three', assigned: true },
];
var reduced = options.reduce(function(filtered, option) {
if (option.assigned) {
var someNewValue = { name: option.name, newProperty: 'Foo' }
filtered.push(someNewValue);
}
return filtered;
}, []);
document.getElementById('output').innerHTML = JSON.stringify(reduced);
<h1>Only assigned options</h1>
<pre id="output"> </pre>
这篇关于同时映射和过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文