将数组转换为嵌套对象

时间:2018-11-28 09:45:57

标签: javascript arrays javascript-objects arrayobject

我有一个对象数组,像这样:

var tryArray = [{
  name: 'name1',
  subname: 'subname1',
  symbolname: 'symbol1'
},
{
  name: 'name1',
  subname: 'subname11',
  symbolname: 'symbol11'
},
{
  name: 'name2',
  subname: 'subname2',
  symbolname: 'symbol2'
},
{
  name: 'name2',
  subname: 'subname22',
  symbolname: 'symbol22'
},
{
  name: 'name3',
  subname: 'subname3',
  symbolname: 'symbol3'
},
{
  name: 'name3',
  subname: 'subname33',
  symbolname: 'symbol33'
}];

我想将此数组转换为嵌套对象,其中名称将是subname的父级,subname将是symbolname的父级。例如:

result = {
  name1: {
    subname1: [symbolname1],
    subname11: [symbolname11] 
  },
  name2: {
    subname2: [symbolname2],
    subname22: [symbolname22] 
  },
  name3: {
    subname3: [symbolname3],
    subname33: [symbolname33] 
  }
}

我已经尝试过使用reduce

tryArray.reduce((object, item) => {
   object[item.name] = {[item.subname]: [item.symbolname]}
},{})

,但它仅返回一个子名称。任何解决方法的想法,非常感谢

1 个答案:

答案 0 :(得分:4)

reduce期望返回值,例如:

var tryArray = [{"name":"name1","subname":"subname1","symbolname":"symbol1"},{"name":"name1","subname":"subname11","symbolname":"symbol11"},{"name":"name2","subname":"subname2","symbolname":"symbol2"},{"name":"name2","subname":"subname22","symbolname":"symbol22"},{"name":"name3","subname":"subname3","symbolname":"symbol3"},{"name":"name3","subname":"subname33","symbolname":"symbol33"}]

var result = tryArray.reduce((object, item) => {
  object[item.name] = object[item.name] || {}; //Need to init name if not exst
  object[item.name][item.subname] = [item.symbolname];
  return object;
}, {})

console.log( result );


如果symbolname中有多个subname,则可以:

var tryArray = [{"name":"name1","subname":"subname1","symbolname":"symbol1"},{"name":"name1","subname":"subname11","symbolname":"symbol11"},{"name":"name2","subname":"subname2","symbolname":"symbol2"},{"name":"name2","subname":"subname22","symbolname":"symbol22"},{"name":"name3","subname":"subname3","symbolname":"symbol3"},{"name":"name3","subname":"subname33","symbolname":"symbol33"}];

var result = tryArray.reduce((object, item) => {
  object[item.name] = object[item.name] || {}; //Need to init name if not exist
  object[item.name][item.subname] = object[item.name][item.subname] || []; //Need to subname name if not exist
  object[item.name][item.subname].push(item.symbolname); //Push the symbolname
  return object;
}, {});

console.log(result);