Javascript - 嵌套的父/子数组递归函数,仅展平父级

时间:2017-08-10 09:07:34

标签: javascript recursion underscore.js

我有一个多维嵌套的父/子数组,如下所示:

{
  parent: {
     name: "foo"
  },
  children: [
    {
      parent: {
         name: "asdf",
      },
      children: []
    },
    {
     parent: {},
     children: []
    },
    {
     parent: {},
     children: []
    },
    ...
  ]
}

我想要做的是在这个数组上应用递归函数,仅展平父属性并保持子节点原样,以便得到这样的结果:

 {
  name: "foo",
  children: [
    {
      name: "asdf",
      children: []
    },
    {
     children: []
    },
    {
     children: []
    },
    ...
  ]
}

我尝试使用underscore.js,但我无法找到可以解决这个问题的递归函数。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您可以通过迭代数组并更新所需属性来使用迭代和递归方法。

如果找到孩子,请再次迭代。



var array = [{ parent: { name: 'a', surname: 'b', }, children: [{ parent: { name: 'c', surname: 'd', }, children: [{ parent: { name: 'e', surname: 'f' } }], childrenName: 'v', childrenSurname: 'w' }], childrenName: 'x', childrenSurname: 'y' }];

array.forEach(function iter(object) {
    if (object.parent) {
        object.name = object.parent.name;
        object.surname = object.parent.surname;
        delete object.parent;
    }
    object.children && object.children.forEach(iter);
});

console.log(array);

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




答案 1 :(得分:0)

希望这个recurse功能是你需要的功能

const recurse = (data) => {
    for(let i = 0, l = data.length; i < l; i++){
        if(data[i]['parent']){
            data[i]['name'] = data[i]['parent']['name']
            delete data[i]['parent']
        }
        if(data[i]['children']) recurse(data[i]['children'])
    }
}