所以,
这是我的JSON数据的一个非常简化的版本:
[
{
"category": "Financial",
"item": "DIAS"
},
{
"category": "Social",
"item": "Andrew Barnett Explains..."
},
{
"category": "Financial",
"item": "FP Sales"
}
]
我希望安排如下:
[
{
"category": "Financial",
"items": [
{
"item": "DIAS"
},
{
"item": "FP Sales"
}
]
},
{
"category": "Social",
"items": [
{
"item": "Andrew Barnett Explains..."
}
]
}
]
实现这一目标的最佳方法(表现明智)是什么?我确信有比使用两个循环更好的方法吗?
由于
答案 0 :(得分:0)
我把一些有用的东西放在一起:http://jsfiddle.net/Hnj2s/
var temp = [
{
"category": "Financial",
"item": "DIAS"
},
{
"category": "Social",
"item": "Andrew Barnett Explains..."
},
{
"category": "Financial",
"item": "FP Sales"
}
];
var output = [];
var lookup = {};
for(var i=0; i<temp.length; i+=1){
var cat = temp[i].category;
if(!lookup[cat]){
lookup[cat] = {
category: cat,
items: []
};
output.push(lookup[cat]);
}
lookup[cat].items.push({
item: temp[i].item
});
}
console.log(output);
我不确定您如何定义最佳方式,您可能需要具体。但是,此方法适用于项目中的单个循环。
答案 1 :(得分:0)
var data = [
{
"category": "Financial",
"item": "DIAS"
},
{
"category": "Social",
"item": "Andrew Barnett Explains..."
},
{
"category": "Financial",
"item": "FP Sales"
}
];
var newData = {};
var res = new Array();
$(data).each(function() {
var cat = this.category;
if (newData[cat] === undefined) {
newData[cat]={};
newData[cat].category = cat;
newData[cat].Items = [{"Item": this.item}];
res.push(newData[cat]);
}
else {
newData[cat].Items.push({"Item": this.item});
}
});
编辑: DEMO:http://jsfiddle.net/dPhg7/
答案 2 :(得分:0)