我有一个对象数组
[
{
classname: ".icon"
data : "12"
},
{
classname: ".icon1"
data : "34"
},
{
classname: ".icon2"
data : "56"
},
{
classname: ".icon"
data : "78"
},
{
classname: ".icon1"
data : "90"
},
{
classname: ".icon1"
data : "AB"
}
]
我想返回按副本分组的数组数组,如此
[
{
classname: ".icon"
data : "12"
},
{
classname: ".icon"
data : "78"
}
]
[
{
classname: ".icon1"
data : "34"
},
{
classname: ".icon1"
data : "90"
},
{
classname: ".icon1"
data : "AB"
}
]
我可以使用lodash以及本机JavaScript。 重要:必须在返回的数组数组中维护其原始出现的顺序。 我正在键入属性名称'classname'
答案 0 :(得分:2)
您可以使用reduce()
var data = [{"classname":".icon","data":"12"},{"classname":".icon1","data":"34"},{"classname":".icon2","data":"56"},{"classname":".icon","data":"78"},{"classname":".icon1","data":"90"},{"classname":".icon1","data":"AB"}]
var obj = {}
var result = data.reduce(function(r, e) {
if (!obj[e.classname]) {
obj[e.classname] = []
r.push(obj[e.classname])
}
obj[e.classname].push(e)
return r;
}, [])
console.log(result)