我有一个对象数组,像这样:
var obj = [{
employeeId: 1300000,
requestValue: 2
}, {
employeeId: 1300000,
requestValue: 3
}, {
employeeId: 1300001,
requestValue: 4
}]
我知道如何使用JavaScript进行操作。但是,如何使用Lodash检索以下结果:
var result = {
1300000: [
{ requestValue: 2 },
{ requestValue: 3 }
],
1300001: [
{ requestValue: 4 }
]
}
答案 0 :(得分:1)
使用Lodash:
这里是示例:
let input = [{"employeeId":1300000,"requestValue":2},{"employeeId":1300000,"requestValue":3},{"employeeId":1300001,"requestValue":4}],
res = _(input)
.groupBy('employeeId')
.mapValues(g => _.map(g, ({requestValue}) => ({requestValue})))
.value();
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
使用普通JavaScript
employeeId
(如果存在),否则使用
空数组requestValue
let input = [{"employeeId":1300000,"requestValue":2},{"employeeId":1300000,"requestValue":3},{"employeeId":1300001,"requestValue":4}],
res = input.reduce((r, {employeeId, requestValue})=> {
(r[employeeId] = r[employeeId] || []).push({requestValue});
return r;
}, {});
console.log(res);