扁平数组与JSON树结构互转

前言

在工作中我们往往可能会遇到无限级别的分类等等的需求,往往后端返回的数据结构可能不是我们想要的数据结构,所以我们来看怎么进行处理

扁平数据结构转换为JSON树型结构

let flatArr = [
  {id: 1, title: "解忧杂货铺1", parent_id: 0},
  {id: 2, title: '解忧杂货铺2', parent_id: 0},
  {id: 3, title: '解忧杂货铺2-1', parent_id: 2},
  {id: 4, title: '解忧杂货铺3-1', parent_id: 3},
  {id: 5, title: '解忧杂货铺4-1', parent_id: 4},
  {id: 6, title: '解忧杂货铺2-2', parent_id: 2},
]

代码

function convert(list) {
  const res = [];
  const map = list.reduce((res, v) => (res[v.id] = v, res), {});
  for (const item of list) {
    if (item.parent_id === 0) {
      res.push(item);
      continue;
    }
    if (item.parent_id in map) {
      const parent = map[item.parent_id];
      parent.children = parent.children || [];
      parent.children.push(item);
    }
  }
  return res;
}
let returnTree = convert(flatArr);
console.log(returnTree);

输出结果

let JsonTree = [
{id: 1, title: '解忧杂货铺1', pid: 0},
  {
    id: 2, title: '解忧杂货铺2', pid: 0, children: [
      {id: 6, title: '解忧杂货铺4-2', pid: 2},
      {
        id: 3, title: '解忧杂货铺2-1', pid: 2, children: [
          {
            id: 4, title: '解忧杂货铺3-1', pid: 3, children: [
              {id: 5, title: '解忧杂货铺4-1', pid: 4},
            ]
          },
        ]
      },
    ]
  }
];

JSON树型结构转换扁平结构

我们看到上面已经有转换好了的JSON树形结构,那么我们如何把上面的结构反推回来呢

代码

function flatten(data) {
  return data.reduce((arr, {id, title, pid, children = []}) =>
    arr.concat([{id, title, pid}], flatten(children)), []);
}
let flatArr = flatten(JsonTree);
console.log(flatArr)

输出结果

[
  {id: 1, title: '解忧杂货铺1', pid: 0},
  {id: 2, title: '解忧杂货铺2', pid: 0},
  {id: 3, title: '解忧杂货铺2-1', pid: 2},
  {id: 4, title: '解忧杂货铺3-1', pid: 3},
  {id: 5, title: '解忧杂货铺4-1', pid: 4},
  {id: 6, title: '解忧杂货铺4-2', pid: 2},
]

结语

利用上面的代码,我们就可以轻松的转换这两种数据结构~
如果大佬们有更好的方法,希望可以发出来一起探讨~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值