[英]How to transform data using Lodash
我对 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}]}}]
]
您需要_.groupBy()
type
,将项目映射到对象,并通过按changeType
再次分组来获取changeType
属性,将项目映射为刚刚更新,并传播结果:
const { map, groupBy, mapValues, pick } = _ const fn = arr => map(groupBy(arr, 'type'), (group, type) => ({ // group and map to array of objects type, ...mapValues( // spread after mapping the values to extract updated groupBy(group, 'changeType'), // group again by changeType items => items.map(item => pick(item, 'updated') // extract the updated from each item )) })) const 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}}] const result = fn(sample) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
为了达到预期,您需要使用用于type
对象的相同逻辑:
const { map, groupBy, mapValues, pick } = _ const fn = arr => map(groupBy(arr, 'type'), (group, type) => ({ // group and map to array of objects type, changeTypes: map( // spread after mapping the values to extract updated groupBy(group, 'changeType'), // group again by changeType (items, changeType) => ({ changeType, updated: items.map(item => item.updated) // extract the updated from each item }) ) })) const 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}}] const result = fn(sample) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.