1

I have an array containing parent child relationship as shown below:

[{
    Company: 'ABC',
    Employees: [{ Company: 'ABC', Name: 'EMP-1' }, 
                { Company: 'ABC', Name: 'EMP-2' }, 
                { Company: 'ABC', Name: 'EMP-3' }]
},
{
    Company: 'XYZ',
    Employees: [{ Company: 'XYZ', Name: 'EMP-4' }, 
                { Company: 'XYZ', Name: 'EMP-5' }, 
                { Company: 'XYZ', Name: 'EMP-6' }]
}]

And using UnderscoreJS's _.flatten method, I want to all elements at same level 0 as shown below:

[{ Company: 'ABC' }
 { Company: 'ABC', Name: 'EMP-1' }, 
 { Company: 'ABC', Name: 'EMP-2' }, 
 { Company: 'ABC', Name: 'EMP-3' },
 { Company: 'XYZ' }, 
 { Company: 'XYZ', Name: 'EMP-4' }, 
 { Company: 'XYZ', Name: 'EMP-5' }, 
 { Company: 'XYZ', Name: 'EMP-6' }]

But I don't know how to achieve this.

2 Answers 2

1

Here's an underscore solution that first maps across the data to return an array of the company without the Employees array and the Employees array. These arrays are then flattened.

var result = _.chain(data)
    .map( company => [_.omit(company, 'Employees'), company.Employees])
    .flatten()
    .value();
Sign up to request clarification or add additional context in comments.

Comments

0

My solution with pure JS:

var array = [{
    Company: 'ABC',
    Employees: [{ Company: 'ABC', Name: 'EMP-1' }, 
                { Company: 'ABC', Name: 'EMP-2' }, 
                { Company: 'ABC', Name: 'EMP-3' }]
},
{
    Company: 'XYZ',
    Employees: [{ Company: 'XYZ', Name: 'EMP-4' }, 
                { Company: 'XYZ', Name: 'EMP-5' }, 
                { Company: 'XYZ', Name: 'EMP-6' }]
}]

var result = array.reduce(function(store, object, index) {
  var arrayOfEmployees = object.Employees;

  delete object.Employees;
  store.push(object);

  return store.concat(arrayOfEmployees)
}, []);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.