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 );
}
The problem with this is the kids
object has an empty first element. How can I circumvent it? If I don't declare it as a JSON object, I can't access the push
element.
Thanks
Just declare kids as an empty array:
var kids = [];
It sounds like you want to end up with a JavaScript object containing several instances of objects that have two keys value
and children
. It would seem an array is the best choice (which Khnle's and Chris's answers give you):
[{"value":2,"children":3}, {"value":12,"children":9}, {"value":20,"children":13}]
In your comment to one of the answers, however, you said that you did not want an array. One way to do this is to wrap it, as in Jergason's answer:
{
"children": [
{"value":2,"children":3},
{"value":12,"children":9},
{"value":20,"children":13}
]
}
Your question seemed to say that you like arrays because you get the push
operation, but you would like to avoid them completely. The only way to avoid arrays completely is to tag each object with its own unique key. If indeed this is what you want, it would look like this:
{
"child0":{"value":2,"children":3},
"child1":{"value":12,"children":9},
"child2":{"value":20,"children":13}
}
This is not hard to do; just replace kids.push(child)
with kids["child" + i] = child
.
Make sure this is really what you want, though, because this collection of children really seems to scream "array"! :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With