正在寻找JavaScript数组插入方法



在特定索引处更新数组的元素。我想用对象的id替换索引1,值保持不变。

const Obj = {
id: 10,
value: "Extra stuff"
}
const Array = [
{
id: 1,
value: "Val 1"
},
{
id: 2,
value: "Val 2"
},
{
id: 3,
value: "Val 3"
},
]

预期结果应为:

const Array = [
{
id: 1,
value: "Val 1"
},
{
id: 10,
value: "Val 2"
},
{
id: 3,
value: "Val 3"
},
]

尝试过这个,但不完整:

const newArray = [...Array.slice(0,1), Obj.id, ...Array.slice(1)]
console.log(newArray);

修复您所面临的问题。

使用以下逻辑创建一个新数组。这将根据您的需求正确创建一个新阵列。。

[...myArray.slice(0, 1), { ...myArray[1], ...{id: myObj.id}}, ...myArray.slice(2)]

const myObj = {
id: 10,
value: "Extra stuff"
}
const myArray = [
{
id: 1,
value: "Val 1"
},
{
id: 2,
value: "Val 2"
},
{
id: 3,
value: "Val 3"
},
]
const newArray = [...myArray.slice(0, 1), { ...myArray[1], ...{id: myObj.id}}, ...myArray.slice(2)]
console.log(newArray);

实现良好的深度复制逻辑。将整个数组复制到一个新变量中,并更新索引1处对象的id。

const myObj = {
id: 10,
value: "Extra stuff"
}
const myArray = [
{
id: 1,
value: "Val 1"
},
{
id: 2,
value: "Val 2"
},
{
id: 3,
value: "Val 3"
},
]
// My bad deep copy logic
const newArray = JSON.parse(JSON.stringify(myArray));
newArray[1].id = myObj.id;
console.log(newArray);
console.log(myArray);

如果您只想更新id(或任何其他特定属性),则可以使用排列运算符(...)

并且尽量不要使用Array等变量名,以避免任何潜在的冲突。

const myObj = {
id: 10,
value: "Extra stuff"
}
const myArray = [
{
id: 1,
value: "Val 1"
},
{
id: 2,
value: "Val 2"
},
{
id: 3,
value: "Val 3"
},
]
// Find the index of the item with ID=2
const indexOfId2 = myArray.findIndex(item => item.id === 2)
myArray[indexOfId2] = {...myArray[indexOfId2], id: myObj.id}
console.log(myArray)

最新更新