lodash进行数据格式化

时间:2019-04-04 23:30:44

标签: javascript json lodash postgresql-9.2

假设我有以下json数组:

const input = [
  { "tx_type": "215", "dos": "2019-05-02", "payer": "Cigna", "count": 23 },
  { "tx_type": "215", "dos": "2019-05-02", "payer": "SENIORCARE Plus", "count": 75 },
  { "tx_type": "217", "dos": "2019-05-02", "payer": "Aetna", "count": 2 },
  { "tx_type": "215", "dos": "2019-05-03", "payer": "Aetna", "count": 85 },
  { "tx_type": "215", "dos": "2019-05-03", "payer": "TRICARE", "count": 1 },
  { "tx_type": "215", "dos": "2019-05-03", "payer": "Aetna", "count": 5 },
  { "tx_type": "215", "dos": "2019-05-03", "payer": "Cigna", "count": 11 }
]

源自postgres 9.2 db,但是我试图将数据放入dataviz中,以期望数据看起来像这样:

[
  {
    "tx_type": "x215",
    "dos": [
      { "date": "2019-05-02", "SENIORCARE Plus": 75, "Cigna": 23 },
      { "date": "2019-05-03", "Aetna": 96, "TRICARE": 1, "Cigna": 11 }
    ],
  },
  {
    "tx_type": "x215",
    "dos": [
      { "date": "2019-05-02", "Aetna": 2 }
    ]
  }
]

我尝试使用lodash使用.groupBy("tx_type")_.chain(input).nest("tx_type").groupBy("dos").value()按tx_type对对象进行分组,并按tx_type进行过滤,然后尝试对分组进行嵌套/嵌套...

真的,我要做的就是按tx_type进行过滤并将付款人和日期进行分组。

任何输入将不胜感激。而我想升级到较新版本的postgres并不是一个真正的选择。

1 个答案:

答案 0 :(得分:1)

tx_type分组并映射分组。要创建dos属性,请映射组中的项目,按dos进行分组,将结果映射以将每一行转换为{ data, [payer]:count }的对象,然后合并这些对象:

const input = [{"tx_type":"215","dos":"2019-05-02","payer":"Cigna","count":23},{"tx_type":"215","dos":"2019-05-02","payer":"SENIORCARE Plus","count":75},{"tx_type":"217","dos":"2019-05-02","payer":"Aetna","count":2},{"tx_type":"215","dos":"2019-05-03","payer":"Aetna","count":85},{"tx_type":"215","dos":"2019-05-03","payer":"TRICARE","count":1},{"tx_type":"215","dos":"2019-05-03","payer":"Aetna","count":5},{"tx_type":"215","dos":"2019-05-03","payer":"Cigna","count":11}]

const result = _(input)
  .groupBy('tx_type')
  .map((dos, tx_type) => ({
    tx_type,
    dos: _(dos)
      .groupBy('dos')
      .map((g, date) => _.merge({}, 
        ..._.map(g, ({ payer, count }) => ({ date,  [payer]: count }))
      ))
      .value()
  }))
  .value()
  
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>