有什么方法可以使嵌套级别未知的嵌套对象变平/取消嵌套?

时间:2019-07-02 20:35:10

标签: javascript

我有一个嵌套的对象,该对象的嵌套深度未知。这是一个例子。

var a = 
[{
title: "parent1",
id: "1",
children: [{
    title: "child 1",
    id: 2,
    parentid: 1
}, {
    title: "child 2",
    id: 3,
    parentid: 1
}]
}, {
title: "parent 2",
id: 4,
children: [{
    title: "child 1",
    id: 5,
    parentid: 4,
    children: [{
        title: "GRAND CHILD",
        id: 6,
        parentid: 5
    }]
}]
}];`

这是我尝试过的代码...它可以工作,但前提是我知道最糟糕的事情...它也可能不是最有效的

function removeNesting(t){
      let flatTree = [];
          for(var i=0;i<t.length;i++){
          let parent = t[i];
          if(parent.children.length>0){
              for(var ii = 0;ii<parent.children.length;ii++){
                flatTree.push(parent.children[ii]);
              }
              //now that all the children are added to the flatTree remove 
        them from the parent and add the parent
              delete parent.children;
              flatTree.push(parent);
       }
      }
      return(flatTree);
    }

任何帮助都会很棒!谢谢!

我希望在任何给定级别上都不要嵌套这些内容。

1 个答案:

答案 0 :(得分:1)

您可以(即将使用)Array#flatMap来获取没有子对象的对象。

const untree = ({ children = [], ...data }) => [data, ...children.flatMap(untree)];

var tree = [{ title: "parent1", id: "1", children: [{ title: "child 1", id: 2, parentid: 1 }, { title: "child 2", id: 3, parentid: 1 }] }, { title: "parent 2", id: 4, children: [{ title: "child 1", id: 5, parentid: 4, children: [{ title: "GRAND CHILD", id: 6, parentid: 5 }] }] }],
    result = tree.flatMap(untree);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }