简体   繁体   English

将新对象添加到现有对象。 Javascript

[英]Add a new object to an existing object. Javascript

I have read SO and others but more complex For referrence:我已经阅读了SO和其他人,但更复杂 供参考:

let newpage = {
  page_no_3: {
    data1: [{index: 1, text: "test1"}],
    data2: [{index: 1, text: "test2"}],
  }
}

What I want to happen when I add new object:添加新对象时我想发生什么:

let newpage = {
  page_no_3: {
    data1: [{index: 1, text: "test2"}, {index: 2, text: "test3"}, ...]
    data2: [{index: 1, text: "test2"}, {index: 2, text: "test4"}, ...]
  }
}

NOTE: Sorry it should not be an array but an object.注意:对不起,它不应该是一个数组,而是一个对象。

NOTE2: Sorry again.注2:再次抱歉。 it should be Array with objects as elements.它应该是以对象为元素的数组。

PS: When I try to get the data of data1 before inserting, it is giving me an undefined error. PS:当我在插入之前尝试获取data1的数据时,它给了我一个未定义的错误。 I tried it like this:我是这样试的:

let page_no = 'page_no_3'
if (nextpage.length == 0) {
    ///
} else { // Both undefined
    console.log(nextpage[page_no].data1)
    console.log(nextpage["page_no_3"].data1)
}

But if I only console.log(nextpage[page_no]) I can see the {index: 1, text: "test2"}.但是如果我只有console.log(nextpage[page_no])我可以看到 {index: 1, text: "test2"}。

First check that your array exist :首先检查您的数组是否存在:

if(newpage["page_no_3"].data1 === undefined){
   newpage["page_no_3"].data1 = [];
}

Then you can add a new object to data1 :然后你可以向 data1 添加一个新对象:

newpage["page_no_3"].data1.push(myAwesomeObject);

maybe this can help you to understand the difference between arrays and objects也许可以帮助您了解数组和对象之间的区别

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

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