繁体   English   中英

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

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

我创建了一个循环,看来我无意间重写了一个对象属性。

我的代码如下:

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."
        }
    ]
}];

当我查看控制台时,我一次又一次具有相同的sectionId值。 在我看来,这应该可以很好地工作,但是我认为我缺少了一些东西。

有什么建议么?

我已经推断出有关您代码周围环境的一些信息,但是这个小提琴对我有用:

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/

暂无
暂无

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

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