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)

 

posted @ 2020-03-04 22:15  逗伴不是瓣  阅读(1269)  评论(0编辑  收藏  举报