js将树状数组按照条件分成两个数组?-灵析社区

梦想缔造狮

const arr = [ { id: 1, date: "2016-05-02", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" }, { id: 2, date: "2016-05-04", name: "王小虎", address: "上海市普陀区金沙江路 1517 弄" }, { id: 3, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄", children: [ { id: 31, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄", }, { id: 32, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄" }, { id: 33, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄" } ] }, { id: 4, date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1516 弄" }]; 以上数组根据id分成两个数组 const condition = { 2: [], 3: [31, 33] } // 分成 const arr1 = [ { id: 1, date: "2016-05-02", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" }, { id: 3, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄", children: [ { id: 32, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄" }, ] }, { id: 4, date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1516 弄" }]; const arr2 = [ { id: 2, date: "2016-05-04", name: "王小虎", address: "上海市普陀区金沙江路 1517 弄" }, { id: 3, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄", children: [ { id: 31, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄", }, { id: 33, date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄" } ] }] 请问应该怎么解决?

阅读量:14

点赞量:0

问AI
const arr = [...] const condition: Record = { 2: [], 3: [31, 33] } const r = arr.reduce((p, c) => { if (c.id in condition) { if (c.children) { const [a, b] = c.children.reduce( ( [a, b], cc, ) => (condition[c.id].includes(cc.id) ? [a, [...b, cc]] : [[...a, cc], b]), [[], []] as typeof arr[], ) if (a.length) p[0].push({ ...c, children: a }) p[1].push({ ...c, children: b }) } else p[1].push(c) } else p[0].push(c) return p }, [[], []] as typeof arr[]) console.log(r)