向现有数组添加对象会覆盖数值。

huangapple go评论126阅读模式
英文:

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: {
    &quot;raucher&quot;: &quot;true&quot;
}

After the second iteration and adding the 2nd object I get

data: {
       &quot;alter&quot;: &quot;65&quot;, 
       &quot;raucher&quot;: false &lt;--- why false?
}

What's going wrong?

  var arr = new Array();

  for (var i = 0; i &lt; componentsLength; i++) {

      var path = formComponentsArray[i].path;

      for (var z = 0; z &lt; payloadLength; z++) {

        var fieldID = payload[z].fieldID.toLowerCase();

        if(path === fieldID) {
          var value = payload[z].value;
          var obj = {};
          obj[path] = value;
          arr[&quot;data&quot;] = { ...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[&quot;data&quot;] = { ...obj };

You are destroying the whole of arr[&quot;data&quot;] 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[&quot;data&quot;] = { [path]:payload[z].value };
   }

Did you mean this?

   if(path === fieldID) {
      arr[&quot;data&quot;][path] = payload[z].value ;
   }

huangapple
  • 本文由 发表于 2023年3月9日 21:23:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定