最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create jQuery array from JSON - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Feb 14, 2013 at 2:56 user988544user988544 5761 gold badge12 silver badges32 bronze badges 1
  • 1 Try aResult={};aResult[name]=value; or something like that. – Passerby Commented Feb 14, 2013 at 3:00
Add a ment  | 

3 Answers 3

Reset to default 5

This should do it

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

Demo: Fiddle

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

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

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);
  });
发布评论

评论列表(0)

  1. 暂无评论