带对象的扁平数组

时间:2017-05-17 20:06:05

标签: javascript arrays

我确定这个问题很常见,但我似乎无法找到一个可靠的答案来解决我的用例。

我有一个嵌套在两个级别的对象数组。以下是该数组的示例:

let array = [
{ company: 'CompanyName1',
    child: [
        { title: 'title1a',
        baby: [
            { title: 'title1ab' },
            { title: 'title1abc' }
        ]
        },
        { title: 'title2a',
        baby: [
            { title: 'titleb2abcd' },
            { title: 'titleb2abcde' }
        ]
        }           
    ]
},
{ company: 'CompanyName2',
    child: [
        { title: 'title2b',
        baby: [
            { title: 'titleb3ab' },
            { title: 'titleb3abc' }
        ]
        }        
    ]
}
]

这是我期待的数组:

    let newArray = [
    { 
     company: 'companyName1',
     child_title_0: 'title1a',
     child_title_1: 'title1a', 
     child_baby_0: 'title1ab',
     child_baby_1: 'title1abc',
     child_baby_2: 'title1abcd',
     child_baby_3: 'title1abcde',  
    },
    { 
     company: 'companyName2',
     child_title_0: 'title2b',
     child_baby_0: 'titleb3ab',
     child_baby_1: 'titleb3abc',
    }
    ]

基本上我需要展平数组的每个顶级对象。由于嵌套对象具有相同的键(遵循模型,并且是动态的 - 一些项目有10个嵌套对象,一些0等)我必须动态生成每个新键,可能基于循环的索引。

任何帮助 - 表示赞赏。

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用map函数返回数组中每个对象的操作版本。

let results = [
  { 
    company: 'CompanyName1',
    child: [
        { 
          title: 'title1a',
          baby: [
            { title: 'title1ab' },
            { title: 'title1abc' }
          ]
        },
        { 
          title: 'title2a',
          baby: [
            { title: 'titleb2abcd' },
            { title: 'titleb2abcde' }
          ] 
        }           
    ]
  },
  { 
    company: 'CompanyName2',
    child: [
        { 
          title: 'title2b',
          baby: [
            { title: 'titleb3ab' },
            { title: 'titleb3abc' }
          ]
        }        
    ]
  }
];

let flattened = results.map(company => {
  let childCount = 0, babyCount = 0;
  company.child.forEach(child => {
    company['child_title_'+childCount] = child.title;
    child.baby.forEach(baby => {
      company['child_baby_'+babyCount] = baby.title;
      babyCount++;
    });
    childCount++;
  });
  delete company.child;
  return company;
});

console.log(flattened);