假设我有一个类似于结构的JSON
[{
"name": "name1",
"custitem_color": "3",
"custitem_ribbon": "1",
"baseprice": "10.00",
"cost": "12.00"
}, {
"name": "name2",
"custitem_color": "4",
"custitem_ribbon": "2",
"baseprice": "20.00",
"cost": "15.00"
}, {
"name": "name3",
"custitem_color": "6",
"custitem_ribbon": "3",
"baseprice": "30.00",
"cost": "22.00"
}, {
"name": "name4",
"custitem_color": "8",
"custitem_ribbon": "4",
"baseprice": "40.00",
"cost": "18.00"
}]
我想生成输出
"name": ["name1","name2","name3"],
"custitem_color":["3","4","6","8"]
我搜索了SO,但没有得到这种类型的匹配。我很想知道是否有任何库或解决方法可以将所有关键值作为单独的数组获得,如上所述。任何建议或指向任何资源将不胜感激。
答案 0 :(得分:2)
试试这个
var result = {},
len = data.length, i, prop;
for (i = 0; i < len; i++) {
for (prop in data[i]) {
if (!result[prop]) {
result[prop] = [];
}
result[prop].push(data[i][prop]);
}
}
答案 1 :(得分:2)
你可以用两个循环来做到这一点。一个循环遍历数组中的每个对象,另一个循环遍历每个单独对象的属性。从那里,您可以构建一个包含分组值的新对象。试试这个:
var output = {};
for (var i = 0; i < data.length; i++) {
for (var item in data[i]) {
output[item] ? output[item].push(data[i][item]) : output[item] = [data[i][item]];
}
}
此方法的好处是可以完全不知道输入对象的格式。如果添加新属性,或者格式是动态的,则代码不需要任何更改。
答案 2 :(得分:0)
var a = [ {"name":"name1", "custitem_color":"3", "custitem_ribbon":"1", "baseprice":"10.00", "cost":"12.00"}, {"name":"name2", "custitem_color":"4", "custitem_ribbon":"2", "baseprice":"20.00", "cost":"15.00"}, {"name":"name3", "custitem_color":"6", "custitem_ribbon":"3", "baseprice":"30.00", "cost":"22.00"}, {"name":"name4", "custitem_color":"8", "custitem_ribbon":"4", "baseprice":"40.00", "cost":"18.00"} ]
var finalobj = {name : [],custitem_color : [],custitem_ribbon : [],baseprice : [],cost : []};
$.each(a,function(pos,val){
finalobj.name.push(val.name);
finalobj.custitem_color.push(val.custitem_color);
finalobj.custitem_ribbon.push(val.custitem_ribbon);
finalobj.baseprice.push(val.baseprice);
finalobj.cost.push(val.cost);
})
console.log(finalobj);
答案 3 :(得分:0)
var final_json = {"name":[],
"custitem_color":[],
"custitem_ribbon":[],
"baseprice":[],
"cost":[]
};
var init_json = [ {
"name":"name1",
"custitem_color":"3",
"custitem_ribbon":"1",
"baseprice":"10.00",
"cost":"12.00"
},
{
"name":"name2",
"custitem_color":"4",
"custitem_ribbon":"2",
"baseprice":"20.00",
"cost":"15.00"
},
{
"name":"name3",
"custitem_color":"6",
"custitem_ribbon":"3",
"baseprice":"30.00",
"cost":"22.00"
},
{
"name":"name4",
"custitem_color":"8",
"custitem_ribbon":"4",
"baseprice":"40.00",
"cost":"18.00"
}
] ;
$.each(init_json ,function(pos,val){
final_json.name.push(val.name);
final_json.custitem_color.push(val.custitem_color);
final_json.custitem_ribbon.push(val.custitem_ribbon);
final_json.baseprice.push(val.baseprice);
final_json.cost.push(val.cost);
})