3👍
✅
You can use .flatMap()
with an inner .map()
and destructuring assignment to convert your nested module arrays into individual objects like so:
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;} /* ignore */
.flatMap()
does have limited browser support, so you can use .reduce()
if you need something more browser compatible:
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;} /* ignore */
Source:stackexchange.com