数组json生成数组树json

var data2 = [
    {id: 0 , val: 'aaa'},
    {id: 0 , val: 'bbb'},
    {id: 2 , val: 'ccc'},
    {id: 1 , val: 'ddd'},
    {id: 1 , val: 'eee'}
]    

var result = [...new Set(data2.map(row=> row.id))].map((item)=>{
 return {
    id: item,
    children: data2.filter(row => row.id == item).map((row)=> ({val: row.val}))
  }
})

// result = [ {id: 0 , children: [{val: 'aaa'},{val: 'bbb'} ]},{id: 2 , children: [{val: 'ccc'}]},{id: 1 , children: [{val: 'ddd'},{val: 'eee'}]} ]
 
多个相同id的对象组合成一个对象,并生成children字段,children为其val的集合
posted @ 2021-12-16 16:04  yanghaogogogo  阅读(40)  评论(0编辑  收藏  举报