skip to Main Content

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


  1. A more simplified approach would be to use flatmap and map like below:

    let companies = [
      { name: 'company 1', depts: ['dept1', 'dept2'], address: 'address1' },
      { name: 'company 2', depts: ['dept2', 'dept3'], address: 'address2' }
    ];
    
    let flattenedCompanies = companies.flatMap(company =>
      company.depts.map(dept => ({
        name: `${company.name} - ${dept}`,
        depts: company.depts,
        address: company.address
      }))
    );
    
    console.log(JSON.stringify(flattenedCompanies));
    Login or Signup to reply.
  2. You can try and reduce the array to what you want.

    var companies = [
      {name: 'company 1', depts : ['dept1', 'dept2'], address: 'address1'},
      {name: 'company 2', depts : ['dept2', 'dept3'], address: 'address2'}
    ];
    
    var res = companies.reduce((acc, item) => ([
       ...acc,
       ...item.depts.map(dept => (
         {...item, name: `${item.name} - ${dept}`}
       ))
    ]), [])
    
    console.log(res)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search