简体   繁体   English

尝试在对象Javascript中创建嵌套数组

[英]Trying to create nested array within an Object Javascript

I have created a loop, and it appears that I am unintentionally rewriting over an object property. 我创建了一个循环,看来我无意间重写了一个对象属性。

My code is the following: 我的代码如下:

Object.keys(existingComments1).forEach(function(key) {
    console.log(existingComments1[key]['sectionId']);
    comment.sectionId = existingComments1[key]['sectionId'];
    existingComments.push(comment);
});

[{
    "sectionId": "3",
    "comments": [
        {
            "id": 66,
            "authorAvatarUrl": "support/images/clay_davis.png",
            "authorName": "Senator Clay Davis",
            "authorId": 3,
            "comment": "These Side Comments are incredible. Sssshhhiiiiieeeee."
        }
    ]
}];

When I look into the console I have the same sectionId value over and over again. 当我查看控制台时,我一次又一次具有相同的sectionId值。 In my mind, this should work perfectly, but I think I am missing something. 在我看来,这应该可以很好地工作,但是我认为我缺少了一些东西。

Any suggestions? 有什么建议么?

I've inferred a few things about the environment around your code, but this fiddle works for me: 我已经推断出有关您代码周围环境的一些信息,但是这个小提琴对我有用:

existingComments = []
existingComments1 = { foo: {sectionId: 1}, bar: {sectionId:3} }

Object.keys(existingComments1).forEach(function(key) {
  console.log(existingComments1[key]['sectionId']);
  comment = {}
  comment.sectionId = existingComments1[key]['sectionId'];
  existingComments.push(comment);
});

https://jsfiddle.net/e7z5btng/ https://jsfiddle.net/e7z5btng/

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

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