js将二维数组对象转化为一维数组对象

let arr = [


  {

    a: 1,

    b: 2,

    c: 3,

    children: [

      {

        id: 1,

        a: 1-1,

        b: 1-2,

        c: 1-3,

      }

    ]

  },

  {

    a: 2-1,

    b: 2-2,

    c: 2-3,

    children: []

  }

]

要将数据格式变成

https://img4.mukewang.com/5caaf7f0000143b402640343.jpg

同时每个对象添加一个唯一的key值

function getData (arr) {

arr.forEach((item, index) => {


brr.push( Object.assign(item, {key: index}) )

if (item.children) {

  getData(item.children)

}

delete item.children;

})

return brr

}

getData(arr)


我写了个提取的方法 children提取出来了,但是原来的children还是存在,而且key值也不是唯一的

https://img3.mukewang.com/5caaf7fc0001c08004290106.jpg

慕田峪9158850
浏览 3211回答 4
4回答

海绵宝宝撒

下面一段程序供参考, 层级多深都能支持。解释下这里用for不用forEach的原因,for在当前循环判断生效后,往arr添加后面添加子项,并会影响到下次循环,而forEach则不然。本来for的这个特性是个缺陷,ES5 forEach的出现也是为了弥补这个缺陷,但是事无绝对,用得好就是优势。for(let item of arr) {&nbsp; &nbsp; if(item.children) {&nbsp; &nbsp; &nbsp; &nbsp; arr = arr.concat(item.children);&nbsp; &nbsp; &nbsp; &nbsp; delete item.children&nbsp; &nbsp; }}console.log(arr);如果要求保持顺序, 下面代码参考下for(let i=0; i < arr.length ; i++) {&nbsp; &nbsp; if(arr[i].children) {&nbsp; &nbsp; &nbsp; arr = arr.slice(0,i+1).concat(arr[i].children,arr.slice(i+1))&nbsp; &nbsp; &nbsp; delete arr[i].children&nbsp; &nbsp; }}console.log(arr);PS:能用循环解决的问题,就不要用递归,如果层次太深,内存吃不消不说,还有可能调用栈溢出,程序崩溃。由于题主是图片, 测试代码我也贴一下吧:let arr = [&nbsp; {&nbsp; &nbsp; a:1,&nbsp; &nbsp; b:2,&nbsp; &nbsp; c:3,&nbsp; &nbsp; children: [&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; id:1,&nbsp; &nbsp; &nbsp; &nbsp; a: 1-1,&nbsp; &nbsp; &nbsp; &nbsp; b: 1-2,&nbsp; &nbsp; &nbsp; &nbsp; c: 1-3&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; id: 2,&nbsp; &nbsp; &nbsp; &nbsp; a: 1-1,&nbsp; &nbsp; &nbsp; &nbsp; b: 1-2,&nbsp; &nbsp; &nbsp; &nbsp; c: 1-3,&nbsp; &nbsp; &nbsp; &nbsp; children: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id:3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a: 1-1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b: 1-2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c: 1-3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; children: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id: 4,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a: 1-1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b: 1-2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c: 1-3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]&nbsp; },&nbsp; {&nbsp; &nbsp; a: 2-1,&nbsp; &nbsp; b: 2-2,&nbsp; &nbsp; children: []&nbsp; }]

四季花海

lodash了解一下

ABOUTYOU

注意你的push是在判断外面,依旧会执行
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript