8

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.

2
  • 3
    It's a JavaScript object literal, NOT JSON. Commented Sep 30, 2013 at 18:42
  • 1
    Please, don't use the word "JSON", there's no JSON at all here. Commented Sep 30, 2013 at 18:43

2 Answers 2

10

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.