数据例子:
let ary = [{name: '1', child: [{id: 1, label: '1'}, {id: 2, label: '2'}]}, {name: '2', child: [{id: 3, label: '3'}, {id: 4, label: '4'}]}]
递归方法:
var flatten = (arr, prev = {}) => { return arr.reduce((pre, cur, idx) => { let obj = idx == 0 && prev.child ? {rowSpan: prev.child.length} : {rowSpan: 0}; return pre.concat(Array.isArray(cur.child) ? flatten(cur.child, cur) : {...cur, name: prev.name, ...obj}) }, []) }
最后调用:
var new_arr = flatten(ary); console.log(new_arr); // [{id: 1, label: "1", name: "1", rowSpan: 2}, {id: 2, label: "2", name: "1", rowSpan: 0}, {id: 3, label: "3", name: "2", rowSpan: 2}, {id: 4, label: "4", name: "2", rowSpan: 0}]