将对象数组推入对象数组

时间:2019-08-21 12:16:44

标签: javascript arrays

我有以下对象数组 我有一个数组,我将数据推入其中。我也希望第三个对象也成为对象(doc3),并且也从其中包含things的另一个对象(forEach)推送数据。我在做什么错了?

var obj = {
  documents: []
};

function print() {
  obj.documents.push({
    "doc1": "",
    "doc2": "",
    "doc3": []

  });

  things.data.forEach(function(item) {
    obj.documents.doc3.push({
      "id": item.id1,
      "id2": item.id2,
      "id3": ""
    });
  });
  
  alert(JSON.stringify(obj));
}

print();

2 个答案:

答案 0 :(得分:1)

json对象中的文档也是一个数组,因为您将对象推入其中

json.documents.push({
         "doc1": "",    
         "doc2": "",
         "doc3":[]
  }); 

如果需要,可以使用

访问doc3。
json.documents[0].doc3

或者,如果您不希望json.documents成为数组,请像这样初始化它

json.documents = {
    "doc1": "",    
    "doc2": "",
    "doc3":[]
};

答案 1 :(得分:0)

在您的代码中,当您将对象推入数组中时...

obj.documents.push({
  "doc1": "",
  "doc2": "",
  "doc3": []
});

对象发生在索引为0的数组的第一个插槽中。

所以代替这个...

// This is wrong
json.documents.doc3.push({
  "id": item.id1,
  "id2": item.id2,
  "id3": ""
});

您必须指定初始对象所在的数组索引(我们知道它是索引0),因此您应该执行以下操作

// This is the right way
json.documents[0].doc3.push({
  "id": item.id1,
  "id2": item.id2,
  "id3": ""
});