var list = [{
"cid": "1",
"type": "图书",
"pid": "0",
"type": "1"
}, {
"cid": "2",
"type": "音像",
"pid": "0",
"type": "1"
}, {
"cid": "3",
"type": "电子书",
"pid": "0",
"type": "1"
}, {
"cid": "4",
"type": "家用电器",
"pid": "0",
"type": "2"
}];
// 保存 type 到 items 数组的映射表
var types = {};
// 按 list 中 type 的顺序生成新的列表
// 每个元素都是一个 { type, items }
var newList = [];
list.forEach(function(item) {
var typeItems = types[item.type];
// typeItems 无值说明映射表里还没加入这个 type
if (!typeItems) {
// 产生一个新的 items 列表
typeItems = [];
// 将 type 这个 items 列表加入映射表
types[item.type] = typeItems;
// 因为是个新的 type,所以加入 newList
newList.push({
type: item.type,
items: typeItems
});
}
// 这里 items 就是按类型找到的元素组
// 在 items 中加入当前 item
typeItems.push(item);
});
console.log(newList);