JS复杂数据拆分重组
2021-04-11 09:27
标签:二维数组 neu lan children i++ console margin ons child 答案: JS复杂数据拆分重组 标签:二维数组 neu lan children i++ console margin ons child 原文地址:https://www.cnblogs.com/-walker/p/12416594.htmlvar arr = [{id: 1},{id: 2},{id: 3},{id: ‘blank‘},{id: 4},{id: 5},{id: ‘blank‘}, {id: 6},{id: ‘blank‘}]
1. 把 arr转换为二维数组:以blank分割,如下
[ [{id: 1},{id: 2},{id: 3}], [ {id: 4},{id: 5} ], [{id: 6} ]]
var arr = [{id: 0}, {id: 1, name: ‘hr‘}, {id: 2}, {id: 3}, {id: 4, name: ‘hr‘}, {id: 5}, {id: 6}]
2. 把arr转换为:以name为hr拆分并追加到name为hr的chuidren,如下
[{ id: 0 }, { id: 1, name: ‘hr‘, children: [ {id: 2}, {id: 3} ] }, { id: 4, name: ‘hr‘, children: [{id: 5}, {id: 6}] }]
1.
var resetArr = arr.reduce((acc, cur, idx, src) => {
// console.log(acc)
if(cur.id === ‘blank‘) {
idx!== src.length - 1 && acc.push([])
} else {
acc.length === 0 && acc.push([])
acc[acc.length - 1].push(cur)
}
return acc
}, [])
2.
function fn(list) {
var newArr = []
var n = 0;
for (let i = 0; i ) {
const ele = arr[i];
newArr.push(ele)
n = i
if (ele.name === ‘hr‘) {
n = i + 1
console.log(arr[n], ‘---‘);
ele.children = [];
while (n arr[n].name)) {
ele.children.push(arr[n])
n = n + 1
}
i = n - 1;
}
}
return newArr
}
var ss = fn(arr)