4 回答
TA贡献1851条经验 获得超5个赞
你只需要filter和map。
使用filter你将得到那些selected真正有价值的人。用于将这些对象的值map映射slug到数组中。
var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
var newArray = diet.filter(f => f.selected).map(m => m.slug)
console.log(newArray)
TA贡献1871条经验 获得超13个赞
您可以使用方法来过滤选择值为 true 的filter记录。这将返回满足条件的对象数组
var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
console.log(diet.filter(e => e.selected))
如果只想返回slug属性,可以使用filter和map方法组合
var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
console.log(diet.filter(e => e.selected == true).map(e => e.slug))
TA贡献1860条经验 获得超8个赞
Array像这样使用函数filter和的组合map:
let diet= [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
let selected=diet.filter(type=>type.selected).map(selectedType=>selectedType.slug)
console.log(selected)
不幸的是,这需要对数组进行两次迭代,一次过滤掉selected,一次只返回slug
reduce您也可以使用这样的方法获得相同的结果
let diet= [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
let reduced = diet.reduce((filtered, option)=> {
if (option.selected) {
filtered.push(option.slug);
}
return filtered;
}, []);
console.log(reduced)
reduce将是推荐的方法,因为您只在数组上迭代一次
TA贡献1770条经验 获得超3个赞
另一种方式可能是
final newList = diet.fold<List>([], (previousValue, e) {
if (e["selected"]) {
previousValue.add(e["slug"]);
}
return previousValue;
});
添加回答
举报