Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing data to JSON object javascript

Tags:

javascript

I want to push this object to a JSON array

var obj =  {'x':21,'y':32,'z':43};

Since my JSON key:value comes dynamically , I cant access using keys , so i used the loop method .

var str = {xA : []}; //declared a JSON array

for (var key in obj) {

    alert(' name=' + key + ' value=' + obj[key]);

     str.xA.push({
         key :   obj[key]
     })
}

When i alert the values I am getting the keys and values properly, but when I am pushing it to the array my key is always coming as 'key' instead of the actual key like x, y,z as in the code.

Any help is appreciated.

like image 224
Abhi Avatar asked Sep 30 '13 18:09

Abhi


2 Answers

The literal notation does not allow expressions for keys. You need to create the object first and then use the bracket notation instead:

var tmp = {};
tmp[key] = obj[key];
str.xA.push(tmp);
like image 70
ThiefMaster Avatar answered Oct 08 '22 06:10

ThiefMaster


You need to use [] notation, otherwise always the key name will be key and not the value of the key.

 str.xA.push({
     key :   obj[key]
 })

to

   var tmp= {};
   tmp[key] = obj[key]
   str.xA.push(tmp)
like image 22
PSL Avatar answered Oct 08 '22 04:10

PSL