JS复杂数据拆分重组
Posted 九转功成
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS复杂数据拆分重组相关的知识,希望对你有一定的参考价值。
var 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 < arr.length; 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.length && (!arr[n].name)) { ele.children.push(arr[n]) n = n + 1 } i = n - 1; } } return newArr } var ss = fn(arr)
!-- p.p1>
以上是关于JS复杂数据拆分重组的主要内容,如果未能解决你的问题,请参考以下文章