David Henry David Henry - 2 months ago 9
Javascript Question

How to transform array of objects into one object by Lodash

Example from this:

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


to:

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

Answer Source

Try with Array#forEach function .

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)

Or simple do with 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)