js 列表对象根据某一字段分类
其实是这个意思,比如说我有一个列表,数据的样子是下面的样子,一个五种,分了两类,食物和饮料。我们想把这五种东西按照类别进行分类,就可以使用这个方式。
[{
name: '苹果',
type: '食物',
price: '3'
},{
name: '牛奶',
type: '饮料',
price: '2'
},{
name: '香蕉',
type: '食物',
price: '2'
},{
name: '果汁',
type: '饮料',
price: '3'
},{
name: '菠萝',
type: '食物',
price: '4'
}]
直接上代码:
// 数据分类 传进要分类的数据列表
dealWithData(data) {
let c = [];
let d = {};
data.forEach(element => {
if (!d[element.type]) { // 按照type分类
c.push({
type: element.type,
list: [element]
});
d[element.type] = element;
} else {
c.forEach(ele => {
if (ele.type== element.type) {
ele.list.push(element);
}
});
}
});
return c;
}
分完类之后就是 :
[{
type: '食物',
list: [{
name: '苹果',
type: '食物',
price: '3'
},{
name: '香蕉',
type: '食物',
price: '2'
},{
name: '菠萝',
type: '食物',
price: '4'
}]
},{
type: '饮料',
list: [{
name: '牛奶',
type: '饮料',
price: '2'
},{
name: '果汁',
type: '饮料',
price: '3'
}]
}]
就是这个样子,其实还有更多的办法,这是其中一个,其他的可以百度或者自己写一下。