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.
答案 0 :(得分:1)
这是一个下划线解决方案,首先在数据中maps返回没有Employees数组和Employees数组的公司数组。然后这些数组是flattened。
<button class="btn btn-success pull-right" onclick="return xepOnline.Formatter.Format('wrapper', {pageWidth:'216mm', pageHeight:'279mm'});">
<i class="fa fa-print"></i><b>Print</b>
答案 1 :(得分: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; }