此示例:
[
{"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 :(得分:3)
无需使用Lodash
。 Array.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);
答案 1 :(得分: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)
答案 2 :(得分:0)
如果您不想使用for
或reduce
,则此处为lodash one-liner
_(data).keyBy('name').mapValues(() => []).value()