2016-10-25 143 views
0

有一個對象A1 =拼合對象的嵌套陣列在陣列字段

[{name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]}, 
{name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]] 

希望的輸出:

[{name:'x',age:21, addr:{flat:1,add:'xyz'}}, 
{name:'x',age:21, addr:{flat:2,add:'xsr'}}, 
{name:'y',age:22, addr:{flat:3,add:'xyz1'}, 
{name:'y',age:22, addr:{flat:4,add:'xsr1'}] 

請建議!我正在嘗試使用lodash /下劃線來完成此操作。

+0

你必須循環陣列之上,併爲每一個元素創建許多新的替代OBJE因爲在'addr'屬性中有cts,沒有什麼困難。 – Azamantes

+0

[下劃線以平坦父/子對象的嵌套數組]可能的重複(http://stackoverflow.com/questions/18003083/underscore-to-flatten-nested-array-of-parent-child-objects) –

回答

0

地圖原始數組到一個新的數組中的每一項,與根據addr場數的項目數。使用concat將所有內容壓扁到一個新的數組中。

如果您使用babel或類似方式轉換爲ES5,您可以使用Object.assign()創建新項目,因爲它不受IE的支持。但是,由於您使用的是角度,因此可以使用angular.extend

ES5:

var arr = [ 
 
    {name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]}, 
 
    {name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]} 
 
]; 
 
    
 
var result = [].concat.apply([], arr.map(function(item) {  
 
    return item.addr.map(function(addr) { 
 
    return angular.extend({}, item, { addr: addr }); 
 
    }); 
 
})); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>

ES6:

const arr = [ 
 
    {name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]}, 
 
    {name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]} 
 
]; 
 
    
 
const result = [].concat(...arr.map((item) => item.addr.map((addr) => Object.assign({}, item, { addr })))); 
 

 
console.log(result);

0

你可以迭代數組和內部數組來構建想要的結果。

var array = [{ name: 'x', age: 21, addr: [{ flat: 1, add: 'xyz' }, { flat: 2, add: 'xsr' }] }, { name: 'y', age: 22, addr: [{ flat: 3, add: 'xyz1' }, { flat: 4, add: 'xsr1' }] }], 
 
    result = array.reduce(function (r, a) { 
 
     return r.concat(a.addr.map(function (b) { 
 
      return { name: a.name, age: a.age, addr: b }; 
 
     })); 
 
    }, []); 
 

 
console.log(result);

ES6

var array = [{ name: 'x', age: 21, addr: [{ flat: 1, add: 'xyz' }, { flat: 2, add: 'xsr' }] }, { name: 'y', age: 22, addr: [{ flat: 3, add: 'xyz1' }, { flat: 4, add: 'xsr1' }] }], 
 
    result = array.reduce((r, a) => r.concat(a.addr.map(b => ({ name: a.name, age: a.age, addr: b }))), []); 
 

 
console.log(result);

0

您可以使用reduce()forEach()Object.assign()返回期望的結果。

var data = [{name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]}, 
 
{name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]}]; 
 

 
var result = data.reduce(function(r, o) { 
 
    o.addr.forEach(function(e) { 
 
    r.push(Object.assign({name: o.name, age: o.age}, e)); 
 
    }) 
 
    return r; 
 
}, []); 
 

 
console.log(result)