如何在JS中处理二维数组转换为一维数组

时间:2019-12-11 03:54:38

标签: javascript vue.js

我得到了如下数组:

[
  {
    companyId: 'TW0826',
    modules: [
      {
        name: 'Module A',
        condition: true,
      },
      {
        name: 'Module B',
        condition: false,
      },
      {
        name: 'Module C',
        condition: true,
      },
    ],
  },
  {
    companyId: 'TXT777',
    modules: [
      {
        name: 'Module B',
        condition: true,
      },
      {
        name: 'Module C',
        condition: false,
      },
      {
        name: 'Module D',
        condition: false,
      },
    ],
  },
];

但我想使它像这样:

[
  {companyId:'TW0826', name:'Module A', condition:ture},
  {companyId:'TW0826',name:'Module B', condition:false},
  {companyId:'TXT777',name:'Module B',condition:ture},
  {companyId:'TXT777',name:'Module C',condition:false}....
]

因此,我可以做些什么来达到上述结果。非常感谢。

1 个答案:

答案 0 :(得分:3)

您可以将.flatMap()与内部.map()destructuring assignment结合使用,将嵌套的模块数组转换为单个对象,如下所示:

const data = [{companyId: 'TW0826', modules: [ { name: 'Module A', condition: true, }, { name: 'Module B', condition: false, }, { name: 'Module C', condition: true, }, ], }, { companyId: 'TXT777', modules: [ { name: 'Module B', condition: true, }, { name: 'Module C', condition: false, }, { name: 'Module D', condition: false, }, ], }, ];

const res = data.flatMap(
  ({companyId, modules}) => 
    modules.map(({name, condition}) => ({companyId, name, condition}))
);

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

.flatMap()的浏览器支持有限,因此如果需要与Bowser兼容的其他东西,可以使用.reduce()

const data = [{companyId: 'TW0826', modules: [ { name: 'Module A', condition: true, }, { name: 'Module B', condition: false, }, { name: 'Module C', condition: true, }, ], }, { companyId: 'TXT777', modules: [ { name: 'Module B', condition: true, }, { name: 'Module C', condition: false, }, { name: 'Module D', condition: false, }, ], }, ];

const res = data.reduce(
  (acc, {companyId, modules}) => 
    [...acc, ...modules.map(({name, condition}) => ({companyId, name, condition}))], []
);

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