2

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.

1
  • 1
    Try aResult={};aResult[name]=value; or something like that. Commented Feb 14, 2013 at 3:00

3 Answers 3

5

This should do it

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

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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);
  });

2 Comments

I am already parsing JSON, I am getting the structure in console, I just don't know how to create an array with it.
Well if you would read my question you'll see am already doing this part.

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.