2

I would like to make a JSON tree from an array. My array is formed like that :

var arraySource = [];
arraySource.push({key : "fr", value: "france"});
arraySource.push({key : "es", value: "spain"});
//...

console.debug(arraySource);

I would like to make a json tree formed like that

var destJson = {
                 "fr" : "france",
                 "es" : "spain"
               };

I don't see how to make this dynamically because to make it I must do

destJson.fr = "france"

but it is not possible because items in the array are dynamics

Any idea ? If you want to play I have made a jsfiddle:

http://jsfiddle.net/lgm42/8L2Kf/1/

Andy
  • 61,948
  • 13
  • 68
  • 95
lgm42
  • 591
  • 1
  • 6
  • 29

3 Answers3

4

In case of dynamic keys in JavaScript there is a square bracket notation:

$.each(arraySource, function(index, item) {
    destJson[item.key] = item.value;
});

DEMO: http://jsfiddle.net/8L2Kf/2/

VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Your code is quite complete. You just need to save values in json.

You can access array directly by

 destJson[item.key]

or

 destJson[item['key']]

and save value contained in:

item.value

or

item['value']

So you have:

destJson[item.key] = item.value;

Demo starting from your code.

Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
0

Create a new object and add the keys to it dynamically using bracket rather than dot notation:

var obj = {};
for (var i = 0, l = arr.length; i < l; i++) {
  obj[arr[i].key] = arr[i].value;
}

DEMO

There's some more information here.

Community
  • 1
  • 1
Andy
  • 61,948
  • 13
  • 68
  • 95