繁体   English   中英

如何附加到空的JSON对象?

[英]How can I append to an empty JSON object?

  var kids = [{}];
  i = 0;
  while (i++ !== count) {
    child = {
      value: Math.floor(Math.random() * 100),
      children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log( kids );
  }

这个问题是kids对象有一个空的第一个元素。 我怎么能绕过它呢? 如果我不将它声明为JSON对象,则无法访问push元素。

谢谢

只需将孩子声明为空数组:

var kids = [];

这听起来像你想与包含有两个键对象的几个实例JavaScript对象落得valuechildren 看起来阵列是最好的选择(Khnle和Chris的答案会给你):

[{"value":2,"children":3}, {"value":12,"children":9}, {"value":20,"children":13}]

但是,在你对其中一个答案的评论中,你说你不想要一个数组。 一种方法是将其包裹起来,如Jergason的回答:

{
    "children": [
        {"value":2,"children":3}, 
        {"value":12,"children":9}, 
        {"value":20,"children":13}
    ]
}

您的问题似乎表明您喜欢数组,因为您获得了push操作,但您希望完全避免它们。 完全避免数组的唯一方法是使用自己的唯一键标记每个对象。 如果这确实是你想要的,它将如下所示:

{
    "child0":{"value":2,"children":3}, 
    "child1":{"value":12,"children":9}, 
    "child2":{"value":20,"children":13}
}

这不难做到; 只需将kids.push(child)替换为kids["child" + i] = child

确保这真的是你想要的,因为这个孩子的集合真的似乎尖叫“阵列”! :-)

您可以让对象包含一个空数组。

var obj = { "children": [] };
// Your looping code here
obj.children.push(child);

稍微改变一下(为局部变量添加var):

var kids = []; //Note this line
var i = 0; //index counter most likely needs to be local
while (i++ !== count) {
    var child = {
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log(kids);
 }

我想这就是你想要的。

更新:您的要求相当奇怪。 你可以这样做:

 var kids = [{}]; //Note this line
 delete kids[0];
 var i = 0; //index counter most likely needs to be local
 while (i++ !== count) {
    var child = {
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log(kids);
 }

要么

 var kids = [{
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
 }];
 var i = 1; //1 less iteration than previous
 while (i++ !== count) {
    var child = {
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log(kids);
 }

这样可以满足你的要求,但我想,我想要的仍然是你想要的。

暂无
暂无

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

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