试图在对象Javascript中创建嵌套数组
我创建了一个循环,似乎是无意中重写了一个对象属性 我的代码如下:试图在对象Javascript中创建嵌套数组,javascript,arrays,Javascript,Arrays,我创建了一个循环,似乎是无意中重写了一个对象属性 我的代码如下: Object.keys(existingComments1).forEach(function(key) { console.log(existingComments1[key]['sectionId']); comment.sectionId = existingComments1[key]['sectionId']; existingComments.push(comment); }); [{
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);
});
什么是
现有评论1
喜欢,你期望得到什么结果?还有什么是评论
?您使用一个对象注释,并将其更新为字段,这样在循环之后,您就有了一个数组,其中有许多指向一个对象的链接,在这里复制我的对象时遇到了问题。我会试试你的建议。可能你需要existingComments.push({sectionId:existingComments1[key]['sectionId']})
你也能提供existingComments1
吗?为什么要删除预期输出?:-)这是可行的,但它需要某种形式。{“sectionId”:“3”,“comments”:[{“id”:66,“authorAvatarUrl”:“support/images/clay_davis.png”,“authorName”:“Senator clay davis”,“authord”:3,“comments”:“这些附带评论令人难以置信。sssshhiiiiieee.”] } ];改变数据结构似乎仍然有效: