如何通过Lodash将对象数组转换为一个对象

时间:2017-07-17 07:56:09

标签: javascript arrays object arraylist 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": []
}

3 个答案:

答案 0 :(得分: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);

答案 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)

如果您不想使用forreduce,则此处为lodash one-liner

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