gpt4 book ai didi

javascript - _.groupBy 动态键

转载 作者:行者123 更新时间:2023-11-30 09:15:14 25 4
gpt4 key购买 nike

我正在使用这个数据结构,并尝试为 (patApplied & insApplied) 键生成一个总对象。

我对在 patApplied 和 insApplied 上使用 _.groupBy 使用动态键名感到困惑(它们可能会根据用户选择而改变)。

我正在尝试 groupBy 映射/减少值以匹配所需的 total 对象

[
{
procedure: '01402',
fee: 82.08,
patApplied: {
'Credit Adjustment': 20,
'User payment': 30
},
insApplied: {
insPayment: 5,
'ins check': 10
}
},
{
procedure: '01801',
fee: 165.16,
patApplied: {
'Credit Adjustment': 0,
'User payment': 10
},
insApplied: {
insPayment: 0,
'ins check': 7
}
}
]

期望的输出

let total = {
patApplied: [ {Credit Adjustment: 20},{User payment: 40} ]
insApplied: [ {insPayment: 10},{ins check: 7} ]
}

最佳答案

通过散布到 _.mergeWith() 中组合对象,然后使用 _.pick() 提取您想要的属性:

const data = [{"procedure":"01402","fee":82.08,"patApplied":{"Credit Adjustment":20,"User payment":30},"insApplied":{"insPayment":5,"ins check":10}},{"procedure":"01801","fee":165.16,"patApplied":{"Credit Adjustment":0,"User payment":10},"insApplied":{"insPayment":0,"ins check":7}}]

const result = _.pick(
_.mergeWith({}, ...data, (obj, src) => _.isNumber(obj) ? obj + src : undefined)
, ['patApplied', 'insApplied'])

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

以及使用 lodash/fp 的同一解决方案的简洁版本和 _.flow():

const { flow, mergeAllWith, cond, isNumber, add, pick } = _

const fn = _.flow(
mergeAllWith(cond([[isNumber, add]])),
pick(['patApplied', 'insApplied'])
)

const data = [{"procedure":"01402","fee":82.08,"patApplied":{"Credit Adjustment":20,"User payment":30},"insApplied":{"insPayment":5,"ins check":10}},{"procedure":"01801","fee":165.16,"patApplied":{"Credit Adjustment":0,"User payment":10},"insApplied":{"insPayment":0,"ins check":7}}]

const result = fn(data)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

关于javascript - _.groupBy 动态键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com