_.group通过动态键

时间:2019-04-07 19:04:43

标签: javascript lodash

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

当使用动态键名(它们可能会根据用户选择而变化)时,我对在patApplied和insApplied上使用_.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} ]
}

2 个答案:

答案 0 :(得分:2)

通过传播到_.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>

答案 1 :(得分:2)

您可以使用Array.prototype.reduce()for..in

const arr = [{"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 = arr.reduce((ac,a) => {
  ['patApplied','insApplied'].forEach(k => {
    for(let key in a[k]){
      ac[k][key] = ac[k][key] || 0;
      ac[k][key] += a[k][key]
      
    }
  })
  return ac;
},{patApplied:{},insApplied:{}})


console.log(total);