admin管理员组文章数量:1317915
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
3 Answers
Reset to default 5This 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);
});
本文标签: javascriptCreate jQuery array from JSONStack Overflow
版权声明:本文标题:javascript - Create jQuery array from JSON - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742022613a2414956.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论