使用reduce实现map

5 javascript ecmascript-6

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
Run Code Online (Sandbox Code Playgroud)

但只是好奇我也知道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
}, [])
Run Code Online (Sandbox Code Playgroud)

小智 8

与其他人的答案类似,更简洁:

items.reduce((accum, o, i) => {
  return [...accum, (o.id === id) ? {...o, name: input} : o];
}, []);
Run Code Online (Sandbox Code Playgroud)