数据源如下:
var arr = [{ "categoryId":123456, "parentId":2010105, "name":"Web解决方案" },{ "categoryId":2010106, "parentId":2010105, "name":"IT解决方案" },{ "categoryId":2010118, "parentId":2010105, "name":"行业解决方案" }]
函数定义:
/** * [groupingData 根据共同字段将数据分组] * @param {[type]} arr [数据源] * @param {[type]} field [字段名] */ const groupingData = (data, filed) => { let map = {}; let dest = []; data.forEach(item => { if(!map[item[filed]]) { dest.push({ [filed]: item[filed], list: [item] }); map[item[filed]] = item; } else { dest.forEach(dItem => { if (dItem[filed] == item[filed]) { dItem.list.push(item); } }); } }) return dest; }
根据数据源可以发现,这里的共同字段是 parentId
let res = groupingData(arr, 'parentId'); console.warn(res);
打印出结果即:
[ { "parentId":2010105, "list":[ { "categoryId":123456, "parentId":2010105, "name":"Web解决方案" }, { "categoryId":2010106, "parentId":2010105, "name":"IT解决方案" }, { "categoryId":2010118, "parentId":2010105, "name":"行业解决方案" } ] } ]