简体   繁体   中英

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. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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