2014-02-19 169 views
0

所以,通过javascript中的属性对JSON数组进行排序?

这是一个非常简化的版本,我的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

尝试建立类似'{“金融“:[”DIAS“,”FP销售“],”社交“:[”Andrew Barnett解释“,...],...}作为中间结果。 – Bergi

+0

你问性能吗,还是你问怎么做?两个循环有什么问题? –

+0

我在问如何以最好的方式做到这一点。 – user1788175

回答

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

谢谢。在这里学到了一些东西。 – user1788175

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/

0

使用下划线方法

_.groupBy 

你能做到这样: jsfiddle

相关问题