gpt4 book ai didi

javascript - 使用扩展运算符更新数组对象对象值

转载 作者:行者123 更新时间:2023-11-30 11:04:48 25 4
gpt4 key购买 nike

我正在尝试更新数组对象和对象的值。我的示例代码如下。没有得到我预期的结果。如果有人能提供帮助就好了?

    let array = [
{
id:"01",
"name": {
"value": "jaison",
"error": null
},
"email": {
"value": "jaison@yopmail.com",
"error": null
}
},
{
id:"02",
"name": {
"value": "jaison 1",
"error": null
},
"email": {
"value": "jaison1@yopmail.com",
"error": null
}
}
];

this.state{
data:array
}

//This two data getting a from a form
const key = "02";
const editedData = {name:"updated jaison 1", email:"updatedjaison1@yopmail.com"}

const newData = [...this.state.data];

const index = newData.findIndex(item => key === item.id);

let item = newData[index];

//Working as expcted
console.log('1', item);

Object.keys(editedData).forEach(function (key) {
item[key] = editedData[key];
});

//Working as expcted
console.log('2', item);

this.setState({ data: [...this.state.data, item]}, () => {
//Not Working as expcted
console.log(this.state.data);
});

Expected result
let array = [
{
id:"01",
"name": {
"value": "jaison",
"error": null
},
"email": {
"value": "jaison@yopmail.com",
"error": null
}
},
{
id:"02",
"name": {
"value": "updated jaison 1",
"error": null
},
"email": {
"value": "updatedjaison1@yopmail.com",
"error": null
}
}
];

最佳答案

当您在 forEach 中更新 item[key] 时,它只会更新 nameemail字符串值。此外,它还会改变 state

相反,您可以通过 editedData 对象循环更新该特定索引的克隆。使用 spread syntax保持 error 和其他属性不变,只更新 value 属性。然后更新克隆的 data 数组的索引并像这样调用 setState:

const key = "02",
editedData = { name: "updated jaison 2", email: "updatedjaison2@yopmail.com" },
data = [...this.state.data],
index = data.findIndex(item => key === item.id),
updatedData = { ...data[index] };

// loop through and update only the keys you need
for(const key in editedData) {
updatedData[key] = { ...updatedData[key], value: editedData[key] }
}

data[index] = updatedData;

this.setState({ data })

关于javascript - 使用扩展运算符更新数组对象对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56107979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com