user2335149
user2335149

Reputation: 75

How to write this in json format?

I have this code that stores the data in array. But I want the output on the json format. Currently, I can convert input data to json but I'm not sure how to change this code that works with object. For example the code on lines :

target = (children[p] || (children[p] = []));

and

target.push({value:item});

Any ideas?

for (var i = 0, len = arry.length; i < len; ++i) {
  var item = arry[i],
      p = item.Parent,
      target = [];

    if(p == rootId) {
        target = roots;
    } 
    else {              
        target = (children[p] || (children[p] = []));           
    }

    target.push({ value: item });

}

Upvotes: 0

Views: 94

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

If you're trying to make the same code work by iterating over a JS object instead of an array, then you probably want this :

for (var key in obj) {
  var item = obj[key];
      p = item.Parent,
      target = [];

    if(p == rootId) {
        target = roots;
    } 
    else {              
        target = (children[p] || (children[p] = []));           
    }

    target.push({ value: item });
}

If you're trying to start from an array but to fill an object, then maybe you want this :

for (var i = 0, len = arry.length; i < len; ++i) {
  var item = arry[i],
      p = item.Parent,
      target = [];

    if(p == rootId) {
        target = roots;
    } 
    else {              
        target = (children[p] || (children[p] = {}));           
    }
    target.value = item;
}

I'd suggest you to read the good MDN introduction on objects and properties : Working with objects

Upvotes: 0

SLaks
SLaks

Reputation: 887767

You can serialize an arbitrary Javascript object to a JSON string by calling JSON.stringify().

That may or may not be what you want.

Upvotes: 2

Related Questions