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
标签:const,name,idx,items,Javascript,newItem,Array,prototype,id From: https://www.cnblogs.com/Answer1215/p/17367615.html