2017-07-17 63 views
1

實施例的變換對象數組到一個對象:如何通過Lodash從這個

[ 
    {"name":"tony", "age":14}, 
    {"name":"jacky", "age":23}, 
    {"name":"lucy", "age":34}, 
    {"name":"sam", "age":15}, 
    {"name":"jay", "age":31} 
] 

到:

{ 
    "tony": [], 
    "jacky": [], 
    "lucy": [], 
    "sam": [], 
    "jay": [] 
} 

回答

0

如果你不喜歡使用forreduce,這裏有一個lodash一個班輪

_(data).keyBy('name').mapValues(() => []).value() 
1

嘗試用Array#forEach功能。

var arr =[ {"name":"tony", "age":14}, {"name":"jacky", "age":23}, {"name":"lucy", "age":34}, {"name":"sam", "age":15}, {"name":"jay", "age":31} ] 
 
var obj={} 
 

 
arr.forEach(function(a){ 
 
obj[a.name]=[] 
 
}) 
 
console.log(obj)

或者簡單做Array#reduce

var arr =[ {"name":"tony", "age":14}, {"name":"jacky", "age":23}, {"name":"lucy", "age":34}, {"name":"sam", "age":15}, {"name":"jay", "age":31} ] 
 

 
var res = arr.reduce((a,b) => (a[b.name]=[] ,a),{}) 
 
console.log(res)

3

沒有必要使用LodashArray.prototype.reduce()將完成這項工作。

const data = [ 
 
    {"name":"tony", "age":14}, 
 
    {"name":"jacky", "age":23}, 
 
    {"name":"lucy", "age":34}, 
 
    {"name":"sam", "age":15}, 
 
    {"name":"jay", "age":31} 
 
]; 
 

 
const result = data.reduce((acc, curr) => { 
 
    acc[curr.name] = []; 
 
    
 
    return acc; 
 
}, {}); 
 

 
console.log(result);