Prevously, when we want to upate an item inside a array:
const items = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
{id: 5, name: 'e'}
]
const newItem = {id: 3, name: 'cc'};
const idx = items.findIndex(i => i.id === newItem.id)
const newItems = [
...items.slice(0, idx),
newItem,
...items.slice(idx + 1)
]
To simpify the process, we can use .with()
const items = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
{id: 5, name: 'e'}
]
const newItem = {id: 3, name: 'cc'}
const newItems = items.with(items.findIndex(i => i.id === newItem.id), newItem)
console.log(newItems)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with
- Javascript prototype Array withjavascript prototype array with javascript prototype mutation tosorted javascript toreversed prototype mutation javascript prototype tospliced mutation javascript prototype proto javascript prototype class and 原型javascript prototype javascript对象array javascript prototype 25 高阶javascript函数array