我如何从平面json创建父子关系?

时间:2018-09-04 10:23:37

标签: javascript

我想以层次结构格式进行数据处理。目前,我通过join从数据库中获取数据,数据格式如下。

[{id:1, name:'India', parentId : ''},
 {id:2, name:'Gujarat', parentId : '1'},
 {id:3, name:'Ahmedabad', parentId : '2'},
 {id:4, name:'Maharastra', parentId : '1'}]

我想要以下格式来绑定treeview和angularjs。

    [
  {
    id: 1,
    name: 'India',
    child: [
      {
        id: 2,
        name: 'Gujarat',
        child: [
          {
            id: 3,
            name: 'Ahmedabad',
            child: [

            ]
          }
        ]
      },
      {
        id: 4,
        name: 'Maharastra',
        child: [

        ]
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:1)

您可以使用array.reduce

但是由于您要向其他对象添加对象,因此需要确保已添加父对象,因此您需要先sort

let places = [{id:1, name:'India', parentId : ''},
  {id:2, name:'Gujarat', parentId : '1'},
  {id:3, name:'Ahmedabad', parentId : '2'},
  {id:4, name:'Maharastra', parentId : '1'}]

// sort to ensure you take care of parents befose children
places = places.sort((i, j) => i.parentId - j.parentId)

let result = []

// you reduce the array
// the accumulator is used to keep easy access to object already processed
places.reduce((acc, place) => {
  // create the new object
  let plc = {id: place.id, name: place.name, childs: []}

  // if there is a parent
  if (place.parentId) {
    // add the current object to the parent
    acc[place.parentId].childs.push(plc)
  } else {
    // or add the current object to the root
    result.push(plc)
  }
  // easy acces to this object
  acc[place.id] = plc
  
  return acc
}, [])

console.log(result)

相关问题