使用jQuery从JSON Response创建对象

时间:2016-03-28 14:07:47

标签: jquery json

我通过AJAX调用以JSON格式从PHP文件中获得响应。

console.log(data["json"]);

[{"value":"23","label":"Assorted Juices"},{"value":"24","label":"Water"},{"value":"25","label":"Beers"},{"value":"26","label":"Carbonated Drinks"},{"value":"27","label":"Instant Beverages "},{"value":"28","label":"Energy Drinks"}]

我能够遍历JSON

var subCategory = data["json"];
//console.log(subCategory);
var obj = $.parseJSON(subCategory);
$.each(obj, function() {
$label = this['label'];
$value = this['value'];
});

我需要在javascript中构建一个类似下面的Object。如何调整上面的循环来生成这样的对象。

var data = [
    { label: 'Water', value: '24' },
    { label: 'Energy Drinks', value: '28' },
]

1 个答案:

答案 0 :(得分:0)

创建一个对象并将其推送到一个数组可以完成这项任务。

var subCategory = data["json"];
//console.log(subCategory);
var obj = $.parseJSON(subCategory);
var data3 = [];
var counter = 0;
$.each(obj, function() {

$label = this['label'];
$value = this['value'];
var obj2 = { 
       label: $label,
       value: $value
   };
   data3.push(obj2);
});