2017-09-14 128 views
1

鑑於我們和對象的數組:具有相同的價值觀推對象數組

let objects = [ 
    {name: 'bob'}, 
    {name: 'foo'}, 
    {name: 'bar'}, 
    {name: 'foo'}, 
    {name: 'foo'} 
] 

我怎樣才能改變這個數組這一個:

let objects = [ 
    [ 
    {name: 'bob'} 
    ], 
    [ 
    {name: 'foo'}, 
    {name: 'foo'}, 
    {name: 'foo'} 
    ], 
    [ 
    {name: 'bar'} 
    ] 
] 

高階函數

回答

2

您可以使用array .reduce() method遍歷數組,並將每個對象放入一個工作對象的數組中,然後使用號屬性的name屬性到工作對象轉換成一個數組的數組:

let objects = [ 
 
    {name: 'bob'}, 
 
    {name: 'foo'}, 
 
    {name: 'bar'}, 
 
    {name: 'foo'}, 
 
    {name: 'foo'} 
 
] 
 

 
let result = Object.values(objects.reduce((a,c) => { 
 
    if (!a[c.name]) a[c.name] = [] 
 
    a[c.name].push(c) 
 
    return a 
 
}, {})) 
 

 
console.log(result)

+0

方式比礦XD漂亮 – rjustin

1

let objects = [{ 
 
    name: 'bob' 
 
    }, 
 
    { 
 
    name: 'foo' 
 
    }, 
 
    { 
 
    name: 'bar' 
 
    }, 
 
    { 
 
    name: 'foo' 
 
    }, 
 
    { 
 
    name: 'foo' 
 
    } 
 
] 
 
let result = objects.reduce((accumulator, currentValue) => { 
 
    if (!Array.isArray(accumulator)) { 
 
    //console.log("once") 
 
    var temp = accumulator; 
 
    accumulator = [ 
 
     [], 
 
     [], 
 
     [] 
 
    ]; 
 
    accumulator[0].push(temp) 
 
    return accumulator; 
 
    } 
 
    
 
    
 

 
    for(var i = 0; i < accumulator.length;i++){ 
 
    //console.log(accumulator[i][0],currentValue.name) 
 

 
    if(accumulator[i][0] == undefined){ 
 
    //console.log("was undefined") 
 
     accumulator[i] =[currentValue] 
 
     return accumulator; 
 
    }else if(accumulator[i][0].name == currentValue.name){ 
 
     //console.log("found match") 
 
     accumulator[i].push(currentValue) 
 
     return accumulator; 
 
    } 
 
    } 
 

 

 

 
    return accumulator; 
 
}); 
 

 
console.log(result)