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
but just curious I also know that reduce is the base for map, foreEach and filter, I would want to try to implement above logic using 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 }, [])
Advertisement
Answer
Similar to other’s answers just more succinct:
items.reduce((accum, o, i) => { return [...accum, (o.id === id) ? {...o, name: input} : o]; }, []);