用新对象替换对象数组

Mic*_*ael 1 javascript arrays object splice ecmascript-6

我有一个对象数组,我想用具有特定 id 的新对象替换一个对象。我的目标是用全新的对象替换/删除 id === 'hotel' 的对象并保持相同的索引。

示例/当前代码

const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]

const index = sampleArray.findIndex((obj) => obj.id === 'hotel1') // find index
sampleArray = sampleArray.splice(index, 0) // remove object at this index
sampleArray.splice(index, 0, { id: 'hotel2' }) // attempt to replace with new object ... not working :(
Run Code Online (Sandbox Code Playgroud)

JDB*_*JDB 5

您不需要花哨的拼接逻辑。只需设置数组元素即可,然后忘记它。

const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]

const index = sampleArray.findIndex((obj) => obj.id === 'hotel1'); // find index
sampleArray[index] = { id: 'hotel2' }; // replace with new object ... working :)

console.log(JSON.stringify(sampleArray));
Run Code Online (Sandbox Code Playgroud)