简体   繁体   English

为什么我的对象键值对被覆盖而不是创建新的键值对?

[英]Why is my objects key, value pair being overridden instead of creating a new key, value pair?

I am trying to create an object of objects within an object with dynamically created key,value pairs, but the nested object keeps overriding the key value pair instead of creating a new key value pair. 我正在尝试使用动态创建的键,值对在对象内创建对象的对象,但是嵌套的对象会不断覆盖键值对,而不是创建新的键值对。

ObjectIDWithQuestions = {};
var ArrayOfBlocks1 = [
  {
    ID: "block1",
    block: "block1",
    BlockElements: [
      { QuestionID: "1"  },
      { QuestionID: "2"  }
    ]
  },
  {
    ID: "block2",
    block: "block2",
    BlockElements: [
      {  QuestionID: "1"  },
      {  QuestionID: "2"  }
    ]
  },
  {
    ID: "block3",
    block: "block3",
    BlockElements: [
      {  QuestionID: "1"  },
      {  QuestionID: "2"  }
    ]
      }
];

for(i=0;i<ArrayOfBlocks1.length;i++){
    for(k=0;k<ArrayOfBlocks1[i].BlockElements.length;k++){
        var ArrayOfBlocks2 = ArrayOfBlocks1[i].ID
        ObjectIDWithQuestions[ArrayOfBlocks2]={}
        ObjectIDWithQuestions[""+ArrayOfBlocks2]["questions"+ k]=ArrayOfBlocks1[i].BlockElements[k].QuestionID

    }
}
console.log(ObjectIDWithQuestions);

The expected result of the code is to create an object that is an object of objects that has a two dynamically created key, value pairs instead of one key, value pair that is being overridden.for example, the following code prints: 该代码的预期结果是创建一个对象,该对象是具有两个动态创建的键值对而不是被覆盖的一个键值对的对象的对象,例如,将打印以下代码:

block1: {questions1: "2"}
block2: {questions1: "2"}
block3: {questions1: "2"}

When it should print 什么时候应该打印

block1: {questions0: "1",questions1:"2"}
block2: {questions0: "1",questions1:"2"}
block3: {questions0: "1",questions1:"2"}

You should initialize 你应该初始化

var ArrayOfBlocks2 = ArrayOfBlocks1[i].ID
ObjectIDWithQuestions[ArrayOfBlocks2]={}

outside the inner loop. 在内循环之外。 Otherwise it will create an object every time the inner loop iterates 否则,每次内部循环迭代时,它将创建一个对象

 ObjectIDWithQuestions = {}; var ArrayOfBlocks1 = [ { ID: "block1", block: "block1", BlockElements: [ { QuestionID: "1" }, { QuestionID: "2" } ] }, { ID: "block2", block: "block2", BlockElements: [ { QuestionID: "1" }, { QuestionID: "2" } ] }, { ID: "block3", block: "block3", BlockElements: [ { QuestionID: "1" }, { QuestionID: "2" } ] } ]; for(i=0;i<ArrayOfBlocks1.length;i++){ var ArrayOfBlocks2 = ArrayOfBlocks1[i].ID ObjectIDWithQuestions[ArrayOfBlocks2]={} for(k=0;k<ArrayOfBlocks1[i].BlockElements.length;k++){ ObjectIDWithQuestions[""+ArrayOfBlocks2]["questions"+ k]=ArrayOfBlocks1[i].BlockElements[k].QuestionID } } console.log(ObjectIDWithQuestions); 

Remove these two lines from inner loop and move it to outside of the inner loop, 从内部循环中删除这两行并将其移到内部循环的外部,

ArrayOfBlocks2 = ArrayOfBlocks1[i].ID
ObjectIDWithQuestions[ArrayOfBlocks2] = {}

This should do the trick 这应该可以解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM