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

时间:2018-12-22 17:30:37

标签: javascript arrays object

我试图在具有动态创建的键值对的对象内创建对象的对象,但是嵌套的对象会不断覆盖键值对,而不是创建新的键值对。

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);

代码的预期结果是创建一个对象,该对象是具有两个动态创建的键值对而不是被覆盖的一个键值对的对象的对象,例如,打印以下代码:

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

何时打印

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

2 个答案:

答案 0 :(得分:1)

您应该初始化

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

在内循环之外。否则,每次内部循环迭代时都会创建一个对象

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);

答案 1 :(得分:0)

从内循环中删除这两行并将其移到内循环之外,

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

这应该可以解决问题