使用javascript将平面数组转换为嵌套数组

时间:2018-05-02 15:34:45

标签: javascript arrays multidimensional-array nested

我希望将这个平面数组转换为嵌套数组,但它会一直返回为空。不知道如何解决这个问题或者我错过了什么,但这让我发疯了。

扁平阵列:

var names =[
{ name: 'b', parent: 'Brown' },
{ name: 'a', parent: 'Brown' },
{ name: 'h', parent: 'Green' },
{ name: 'c', parent: 'Green' },
];

数组的所需输出:

[{
    name: 'Brown',
    children: [{
            name: 'a',
            children: []
        },
        {
            name: 'b',
            children: []
        }
    ]
}, {
    name: 'Green',
        children: [{
                name: 'h',
                children: []
            },
            {
                name: 'c',
                children: []
            }
        ]
    }
}]

JS:

function getNestedChildren(arr, parent) {
    var children = [];
    for(var i =0; i < arr.length; ++i) {
        if(arr[i].parent == parent) {
            var grandChildren = getNestedChildren(arr, arr[i].name)

            if(grandChildren.length) {
                arr[i].children = grandChildren;
            }
            children.push( arr[i]);
        }
    }
    return children;
}
var nest = getNestedChildren(names, names.parent);
console.log( nest);

3 个答案:

答案 0 :(得分:1)

您可以创建一个新对象,为每个项目将一个数组分配给具有父名称的键,并将该项目连接到该数组

var names =[
{ name: 'b', parent: 'Brown' },
{ name: 'a', parent: 'Brown' },
{ name: 'h', parent: 'Green' },
{ name: 'c', parent: 'Green' },
];

const getGroup=(groups, parent) => {
  let group = groups.find(g=>g.parent===parent);
  if(!group){
    group=({parent,children:[]});
    groups.push(group);
  }
  return group;
}

let  grouped = []
 names.forEach(item=> getGroup(grouped,item.parent).children.push(item))
 
                             
console.log(grouped)

答案 1 :(得分:1)

&#13;
&#13;
var names =[
{ name: 'b', parent: 'Brown' },
{ name: 'a', parent: 'Brown' },
{ name: 'h', parent: 'Green' },
{ name: 'c', parent: 'Green' },
{ name: 'j', parent: 'Brown' }
];

function groupBy(arr, f) {
  return arr.reduce((r, v, i, a, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});
}

function nestArray(array){
  var newArray=[],
      resultGrouped = groupBy(names, function(c) {
    return c.parent
  });
  
  for (var key in resultGrouped){
    var item=resultGrouped[key];
    
    newArray.push({
      name:key,
      children:item.map(function(map){
        delete map.parent;
        map.children=[];
        return map;
      })
    });
  }
  
  return newArray;
}
console.log(nestArray(names));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

因此对于初学者,您需要遍历名称并将每个父级发送到getNestedChildren()函数。

var names =[
    { name: 'b', parent: 'Brown' },
    { name: 'a', parent: 'Brown' },
    { name: 'h', parent: 'Green' },
    { name: 'c', parent: 'Green' },
];

var nest = [];

for (var i = 0; i < names.length; i++) {
    nest.push(getNestedChildren(names, names[i].parent));
} 

此外,您的getNestedChildren()当前正在尝试修改并发送回旧名称数组。我建议改为创建一个新对象,并将带有子节点的对象发回去。

function getNestedChildren(arr, parent) {
    var children = [];
    var parentObj = {};
    parentObj.name = parent;
    for(var i =0; i < arr.length; ++i) {
        if(arr[i].parent == parent) {
            children.push(getNestedChildren(arr, arr[i].name));
        }
    }
    parentObj.children = children;
    return parentObj;
}