const items = [{
id: 1,
name: 'ball'
},{
id: 2,
name: 'axe'
}]
//says I want to update item 2
let input = 'laptop', id = 2
updated_item = items.map(o => o.id === id ? ({ ...o, name: input }) : o) });
console.log(updated_item) // worked
但只是好奇,我也知道reduce是map,foreEach和filter的基础,我想尝试使用reduce来实现上述逻辑
const updated_item_using_reduce = items.reduce((accum, o, i) => {
if(o.id === id) {
//what to do here? change value of name put o into accum? by using push?
}
//else have to assign o to accum, but can't use push I think
}, [])
与其他答案类似,更加简洁:
items.reduce((accum, o, i) => {
return [...accum, (o.id === id) ? {...o, name: input} : o];
}, []);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句