[英]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對象落得value
和children
。 看起來陣列是最好的選擇(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.