Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
  }

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

like image 784
Shamoon Avatar asked Sep 08 '11 03:09

Shamoon


2 Answers

Just declare kids as an empty array:

var kids = [];
like image 69
Chris Pietschmann Avatar answered Oct 19 '22 12:10

Chris Pietschmann


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"! :-)

like image 3
Ray Toal Avatar answered Oct 19 '22 12:10

Ray Toal