【发布时间】:2019-12-10 19:42:05
【问题描述】:
我对 lodash 没有太多经验,我想转换我的数据。 我尝试使用 groupBy 和 map 但我无法获得预期的结果。 如果有人可以提供帮助将不胜感激。
样本数据
var sample = [{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
},
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
},
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
]
// what I tried
var result = _.mapValues(_.groupBy(sample, "type"), x => x.map(y => _.omit(y, "changeType")));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
预期结果
var output = [
{
"type": "changeAccount",
1: [{
"updated": 'for changeType 1 under type changeAccount
}],
2: [{
"updated": for changeType 2 under type changeAccount
}]
},
{
"type": "changeProduct",
1: [{
"updated": for changeType 1 under type changeProduct
}]
}
]
预期结果 2
const sample2 = [
{type:"changeAccount", changeType: [{1:[{updated}],{2:[{updated}]}}]
]
【问题讨论】:
标签: javascript collections lodash