英文:
Adding object to existing array overwrites value
问题
我正在循环遍历两个数组并创建一个对象,我想将其添加到我的数据数组中。
在第一次迭代中,我得到
data: {
"raucher": "true"
}
在第二次迭代中,添加第二个对象后,我得到
data: {
"alter": "65",
"raucher": false <--- 为什么是false?
}
出了什么问题?
var arr = new Array();
for (var i = 0; i < componentsLength; i++) {
var path = formComponentsArray[i].path;
for (var z = 0; z < payloadLength; z++) {
var fieldID = payload[z].fieldID.toLowerCase();
if(path === fieldID) {
var value = payload[z].value;
var obj = {};
obj[path] = value;
arr["data"] = { ...obj };
}
}
}
英文:
I'm looping through 2 arrays and create an object which I want to add to my array data.
In the first iteration I get
data: {
"raucher": "true"
}
After the second iteration and adding the 2nd object I get
data: {
"alter": "65",
"raucher": false <--- why false?
}
What's going wrong?
var arr = new Array();
for (var i = 0; i < componentsLength; i++) {
var path = formComponentsArray[i].path;
for (var z = 0; z < payloadLength; z++) {
var fieldID = payload[z].fieldID.toLowerCase();
if(path === fieldID) {
var value = payload[z].value;
var obj = {};
obj[path] = value;
arr["data"] = { ...obj };
}
}
}
答案1
得分: 2
以下是您要翻译的代码部分:
这部分代码有问题
if(path === fieldID) {
var value = payload[z].value;
var obj = {};
obj[path] = value;
arr["data"] = { ...obj };
}
你正在破坏arr["data"]
的整体,并将其替换为只能有一个键的对象。
你能看到上面的写法与下面的写法在效果上是相同的吗?
if(path === fieldID) {
arr["data"] = { [path]: payload[z].value };
}
你是不是想要这样?
if(path === fieldID) {
arr["data"][path] = payload[z].value;
}
英文:
This segment of your code is wrong
if(path === fieldID) {
var value = payload[z].value;
var obj = {};
obj[path] = value;
arr["data"] = { ...obj };
You are destroying the whole of arr["data"]
and replacing it with an object that can only have one key.
Can you see that what is written above is identical in effect to:
if(path === fieldID) {
arr["data"] = { [path]:payload[z].value };
}
Did you mean this?
if(path === fieldID) {
arr["data"][path] = payload[z].value ;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论