JC JC
JC JC

Reputation: 12132

How do I change a JSON object into an array key/value pairs through code?

How do I change a JSON object into an array key/value pairs through code?

from:

{
   'name':'JC',
   'age':22
}

to:

['name':JC,'age':22] //actually, see UPDATE


UPDATE:

...I meant:

[{"name":"JC"},{"age":22}]

Upvotes: 0

Views: 1255

Answers (3)

freedev
freedev

Reputation: 30087

May be you only want understand how to iterate it:

var obj = { 'name':'JC', 'age':22 };
for (var key in obj)
{
    alert(key + ' ' + obj[key]);
}

Update:
So you create an array as commented:

var obj = { 'name':'JC', 'age':22 };
var obj2 = [];
for (var key in obj)
{
    var element = {};
    element[key] = obj[key]; // Add name-key pair to object
    obj2.push(element);      // Store element in the new list
}

Upvotes: 1

Alex Korban
Alex Korban

Reputation: 15126

If you're trying to convert a JSON string into an object, you can use the built in JSON parser (although not in old browsers like IE7):

JSON.parse("{\"name\":\"JC\", \"age\":22}");

Note that you have to use double quotes for your JSON to be valid.

Upvotes: 1

Marat Tanalin
Marat Tanalin

Reputation: 14123

There is no associative array in JavaScript. Object literals are used instead. Your JSON object is such literal already.

Upvotes: 0

Related Questions