一个带有重复对象的数组生成一个树形结构的数组

2019-08-23  本文已影响0人  蜗牛Coming
面试题摘抄记录

如何将 [{id: 1}, {id: 2, pId: 1}, ...] 的重复数组(有重复数据)转成树形结构的数组 [{id: 1, child: [{id: 2, pId: 1}]}, ...] (需要去重)

const fn = arr => {
          const res = []
          const map = arr.reduce((res, item) => ((res[item.id] = item), res), {});
          for (const item of Object.values(map)) {
            if (!item.pId) {
              res.push(item)
            } else {
              const parent = map[item.pId]
              parent.child = parent.child || []
              parent.child.push(item)
            }
          }
        return res
}
// Object.values()返回一个数组,其元素是在对象上找到的可枚举属性值。属性的顺序与通过手动循环对象的属性值所给出的顺序相同。
// reduce  arr.reduce(callback,[initialValue])
callback(total, currentValue, currentIndex, arr)
    total   必需。初始值, 或者上一次调用回调返回的值。
    currentValue    必需。当前元素
    currentIndex    可选。当前元素的索引
    arr 可选。当前元素所属的数组对象。
initialValue (可选。传递给函数的初始值,作为第一次调用 callback 的第一个参数)
const map = arr.reduce((res, item) => ((res[item.id] = item), res), {});
//相当于
var map;
var res = {};
arr.foreach(function(item,index){
    res[item.id] = item;
})
map = res;
上一篇 下一篇

猜你喜欢

热点阅读