怎么把level为2的数据更简便的归类到level为1且 category === parent_category下?level为1的数据下有children:[] 字段,感谢
1 回答
PIPIONE
TA贡献1829条经验 获得超9个赞
如果只有两级的话,用下面这个
const result = arr .filter((a) => a.level === '1') .map(a => ({ ...a, children: arr .filter(_a => _a.level === '2' && _a.parent_category === a.parent) }))
如果有多级的话,用递归
function classify(arr, level = '1', parent_category = '') { const children = arr.filter( a => a.level === `${level}` && a.parent_category === parent_category, ) return children.length === 0 ? children : children.map(a => ({ ...a, children: classify(arr, parseInt(a.level, 10) + 1, a.parent), })) }const result = classify(arr)
添加回答
举报
0/150
提交
取消