user988544
user988544

Reputation: 576

Create jQuery array from JSON

I want to create an associative array in jQuery using the values returned in a JSON object. The JSON object is dynamically created:

[{"name":"key1","value":"value1"},{"name":"key2","value":"value2"},{"name":"key3","value":"value3"},{"name":"key4","value":"value4"}]

I want to create an associative array of this format using the values returned in JSON:

aResult = {key1 : 'value1', key2 : 'value2', key3 : 'value3', key4 : 'value4'};

Currently when I iterate through the JSON object, I can see the desired array structure in console

$.each(jData, function(k, v) {
    if (v.name.toLowerCase().indexOf("answer") >= 0) {
        name = v.name;
        value = v.value;
        console.log(name + ' : ' + value); //returns the structure I wish
    };

});

But when I add this code in the loop to create array

var aResult = {name:value}

It returns [object Object]

What am I missing? How should I go forward? Any help is appreciated.

Upvotes: 2

Views: 8086

Answers (3)

Shobhit Sharma
Shobhit Sharma

Reputation: 1609

First of all you need to parse the json using

$.parseJSON();

it is required to convert JSON to object After that try using

$.each(data, function(n, val) {
    console.log(name + ': name = ' +val.name + ' value = ' + val.value);
  });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

This should do it

var obj = {};
$.each(data, function(i, v){
       obj[v.name] = v.value
   });
console.log(obj)

Demo: Fiddle

Upvotes: 5

Marlos Carmo
Marlos Carmo

Reputation: 972

The command jQuery.parseJSON() convert JSON in a Object.

http://api.jquery.com/jQuery.parseJSON/

Upvotes: 1

Related Questions