【问题标题】:Convert Nested Object into Array of Objects and remove keys将嵌套对象转换为对象数组并删除键
【发布时间】:2018-04-04 03:50:46
【问题描述】:

如何转换这样的对象:

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() 函数,我可以获取对象的值,但在为嵌套对象执行此操作时遇到了麻烦。有什么想法吗?

【问题讨论】:

    标签: javascript ecmascript-6 lodash


    【解决方案1】:

    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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 2015-03-26
      • 2019-01-31
      相关资源
      最近更新 更多