如何使用键值对创建动态对象

时间:2019-10-02 17:30:24

标签: javascript arrays json object

输入数据

var rows = [{
   'type':'action',
   'key':'active_session',
   'count': 4596
},{
   'type':'action',
   'key':'active_session',
   'count': 100
},{
  'type':'action',
  'key':'know_more',
  'count': 100
},{
  'type':"category",
 'key': "reactions",
 'count': 500
}];

预期输出

 {"action": {
        "active_session": 4696,
         "know_more":100
    },
 "category":{
     "reaction": 500 
  }
 }

我有输入数据,不知道如何以最简单的方式实现预期的输出。请帮助我,我将非常感激。

1 个答案:

答案 0 :(得分:4)

您可以使用reduce方法获得所需的结果,并使用一个对象作为累加器值。

var rows = [{"type":"action","key":"active_session","count":4596},{"type":"action","key":"active_session","count":100},{"type":"action","key":"know_more","count":100},{"type":"category","key":"reactions","count":500}]

const result = rows.reduce((r, { type, key, count }) => {
  r[type] = r[type] || {}
  r[type][key] = r[type][key] || 0
  r[type][key] += count
  return r;
}, {})

console.log(result)