I have the following data structure :
var companies = [{name: 'company 1', depts : ['dept1', 'dept2'], address: 'address1'},
{name: 'company 2', depts : ['dept2', 'dept3'], address: 'address2'},];
I want to repeat the company for each department, so I want each company repeated for each one of its departments, and I want the name to be the name of the company with the department.
So I want this exact output:
[{name: 'company 1 - dept1', depts : ['dept1', 'dept2'], address: 'address1'},
{name: 'company 1 - dept2', depts : ['dept1', 'dept2'], address: 'address1'},
{name: 'company 2 - dept2', depts : ['dept2', 'dept3'], address: 'address2'},
{name: 'company 2 - dept3', depts : ['dept2', 'dept3'], address: 'address2'},
];
I am able to achieve this by using two steps, but I want to see if there is a better and more clean way to do it.
companies.forEach(company => company.displayCompanies = company.depts.map(
dept => Object.assign({}, company, {name: `${company.name} - ${dept}`})))
var newCompanies = companies.flatMap(company => company.displayCompanies )
2
Answers
A more simplified approach would be to use
flatmap
andmap
like below:You can try and reduce the array to what you want.