代码之家  ›  专栏  ›  技术社区  ›  Chan

将嵌套对象转换为对象数组并删除关键帧

  •  1
  • Chan  · 技术社区  · 7 年前

    如何转换如下对象:

    const data = 
    {
      "1":{
        name: 'Main Parent',
        descendants: {
          "1":{
            name: "Main Child 1",
            children: {
              "1":{
                name: "Sub Child 1"
              }
            }
          },
          "2":{
            name: "Main Child 2",
            children: {
              "1":{
                name: "Sub Child 1"
              }
            }
          },
    
        }
      }
    }
    

    要删除对象关键帧,然后转换为如下对象阵列:

    const data = [
      {
        name: 'Main Parent 1',
        descendants: [
          {
            name: "Main Child 1",
            children: [
              {
                name: "Sub Child 1"
              }
            ]
          },
          {
            name: "Main Child 2",
            children: [
              {
                name: "Sub Child 1"
              }
            ]
          }
        ]
      }
    ]
    

    已尝试使用lodash。values()函数,我可以获取对象的值,但在为嵌套对象执行此操作时遇到困难。有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   CertainPerformance    7 年前

    对两者都使用递归和测试 children 钥匙和 descendants 密钥:

    const input = {
      "1": {
        name: 'Main Parent',
        descendants: {
          "1": {
            name: "Main Child 1",
            children: {
              "1": {
                name: "Sub Child 1"
              }
            }
          },
          "2": {
            name: "Main Child 2",
            children: {
              "1": {
                name: "Sub Child 1"
              }
            }
          },
    
        }
      }
    };
    
    const output = recursiveTransform(input);
    function recursiveTransform(inputObj) {
      const newArr = Object.values(inputObj);
      newArr.forEach(obj => {
        if (obj.descendants) obj.descendants = recursiveTransform(obj.descendants);
        if (obj.children) obj.children = recursiveTransform(obj.children);
      });
      return newArr;
    }
    console.log(output);