如何将包含数组的对象转换为对象的对象

时间:2017-04-15 12:14:11

标签: javascript html arrays javascript-objects

我的代码:

function convert(arr, parent) {
    var out = [];
    for(var i in arr) {
        if(arr[i].parent == parent) {
            var children = convert(arr, arr[i].id)

            if(children.length) {
                arr[i].children = children
            }
            out.push(arr[i])
        } 
    }
    return out; //return Object.assign({}, out);tried this, but i lose parents childrens arrays
};
arras = [
    {id: 1, name: "parent1", parent: null},
    {id: 2, name: "children1", parent: 1},
    {id: 3, name: "children2", parent: 1},
    {id: 4, name: "parent2", parent: null},
    {id: 5, name: "children3", parent: 4},
    {id: 6, name: "children4", parent: 4}
]
console.log(convert(arras, null));

最终结果应如何显示

{
    parent1: [
        {name: "children1"},
        {name: "children2"}
    ],
    parent2: [
        {name: "children3},
        {name: "children4"}
    ]
}

到目前为止我的输出结果:

[
  {id: 1, name: "parent1", parent: null}: [
        {id: 2, name: "children1", parent: 1},
        {id: 3, name: "children2", parent: 1},
    ],
  {id: 4, name: "parent2", parent: null}: [
        {id: 5, name: "children3", parent: 4},
        {id: 6, name: "children4", parent: 4}
    ]
]

首先,我要做的是将主数组转换为对象,当我倾向于这样做时,我失去了两个父对象数组......还需要更改控制台显示对象的方式,任何帮助都是值得赞赏的。< / p>

5 个答案:

答案 0 :(得分:2)

试试这个。

function convert(arr) {
  var parents = {};
  for (var i in arr) {
    if (arr[i].parent === null) {
      parents[arr[i].id] = arr[i].name
    }
  }

  var out = {}
  for (i in arr) {
    if (arr[i].parent !== null) {
      var parentName = parents[arr[i].parent];
      if (out.hasOwnProperty(parentName)) {
        out[parentName].push(arr[i].name)
      } else {
        out[parentName] = [arr[i].name]
      }
    }
  }
  return out;
};
arras = [{
    id: 1,
    name: "parent1",
    parent: null
  },
  {
    id: 2,
    name: "children1",
    parent: 1
  },
  {
    id: 3,
    name: "children2",
    parent: 1
  },
  {
    id: 4,
    name: "parent2",
    parent: null
  },
  {
    id: 5,
    name: "children3",
    parent: 4
  },
  {
    id: 6,
    name: "children4",
    parent: 4
  }
]
//console.log(convert(arras, null));
alert(JSON.stringify(convert(arras)));

但是注意多级别它无法正常工作。如果您需要,您必须为所有可能的父列表保存地图

答案 1 :(得分:2)

arras.forEach(function(el){
    if(el.parent){
      el.parent=arras.find(e=>e.id==el.parent)||(console.error("no parent:"+el.parent),undefined);
    }
 });
 //resolved parent/childs....
 var newmodel = arras.reduce(function(obj,el){
   if(el.parent){
    //child
    obj[el.parent.name]=obj[el.parent.name]||[];//create new parent if neccessary
    obj[el.parent.name].push({name:el.name});
   }else{
    //parent
    obj[el.name]=obj[el.name]||[];
  }
  return obj;
  },{});

http://jsbin.com/renicijufi/edit?console

答案 2 :(得分:2)

您可以构建一个树,检查父节点是否是根节点。

&#13;
&#13;
var data = [{ id: 1, name: "parent1", parent: null }, { id: 2, name: "children1", parent: 1 }, { id: 3, name: "children2", parent: 1 }, { id: 4, name: "parent2", parent: null }, { id: 5, name: "children3", parent: 4 }, { id: 6, name: "children4", parent: 4 }],
    tree = function (data, root) {
        var r = {},
            o = {};

        data.forEach(function (a) {
            if (a.parent === root) {
                r[a.name] = [];
                o[a.id] = r[a.name];
            } else {
                o[a.parent] = o[a.parent] || [];
                o[a.parent].push({ name: a.name });
            }
        });
        return r;
    }(data, null);

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

答案 3 :(得分:1)

另一种方式:

var arrays = [
    {id: 1, name: 'parent1', parent: null},
    {id: 2, name: 'children1', parent: 1},
    {id: 3, name: 'children2', parent: 1},
    {id: 4, name: 'parent2', parent: null},
    {id: 5, name: 'children3', parent: 4},
    {id: 6, name: 'children4', parent: 4}
];

// First, reduce the input arrays to id based map
// This step help easy to select any element by id.
arrays = arrays.reduce(function (map, el) {
    map[el.id] = el;

    return map;
}, {});

var result = Object.values(arrays).reduce(function (result, el) {
    if (!el.parent) {
        result[el.name] = [];
    } else {
        result[arrays[el.parent].name].push(el.name);
    }

    return result;
}, {});

console.log(result);

答案 4 :(得分:1)

我认为这符合您的要求

Obj = new Object();

for( i in arras){

    person = arras[i];

    if(person.parent != null){
        if(!Obj.hasOwnProperty(person.parent)){
            // here instead of the index you can use Obj["parent"+person.parent] get the exact thing. If you are using that use tha in rest of the code 
            Obj[person.parent] = new Array();
        }

        Obj[person.parent].push(person);    
    }
    else{
        if(!Obj.hasOwnProperty(person.id)){
            // Some parents might have kids not in the list. If you want to ignore, just remove from the else. 
            Obj[person.id] = new Array()
        }
    }
}

编辑:

Obj = new Object();

for( i in arras){

    person = arras[i];

    if(person.parent != null){
        if(!Obj.hasOwnProperty(person.parent)){
            // here instead of the index you can use Obj["parent"+person.parent] get the exact thing. If you are using that use tha in rest of the code 
            Obj[person.parent] = new Array();
        }

        Obj[person.parent].push({name : person.name});  
    }
    else{
        if(!Obj.hasOwnProperty(person.id)){
            // Some parents might have kids not in the list. If you want to ignore, just remove from the else. 
            Obj[person.id] = new Array()
        }
    }
}

希望这会有所帮助。 :)