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

时间:2018-04-04 03:50:47

标签: javascript ecmascript-6 lodash

如何转换像这样的对象:

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 个答案:

答案 0 :(得分:0)

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