根据属性条件合并多个对象数组

时间:2019-02-26 13:54:11

标签: javascript

我有以下JSON:

"A series":[
   {
      "month":"2017 january",
      "value":77.2
   },
   {
      "month":"2017 february",
      "value":11.9
   },
   {
      ...
   }
],
"Main serie":[
   {
      "month":"2017 january",
      "value":3000050.0
   },
   {
      "month":"2017 february",
      "value":6520575.0
   },
   {
      ...
   }
],
"B series":[
   {
      "month":"2017 january",
      "value":55000.0
   },
   {
      ...
   }
]

我想将它们组合成一个看起来像这样的数组:

{
   "month":"2017 january",
   "Main serie":3000050.0,
   "A series":77.2,
   "B series":55000.0
},
{
   "month":"2017 february",
   "Main serie":6520575.0,
   "A series":11.9,
   "B series":75000.0
},
{
   "month":"2017 march",
   "Main serie":6955250.0,
   "A series":66.4,
   "B series":85000.0
},
{
   ...
},

该序列可以是2、3或更多,其中Main系列是主体,我在位置2或3处接收。年/月是重复的值。

1 个答案:

答案 0 :(得分:1)

您可以像这样使用嵌套的reduce。创建一个具有唯一month作为键的累加器,并不断对其进行更新

const input={"A series":[{"month":"2017 january","value":77.2},{"month":"2017 february","value":11.9},],"Main serie":[{"month":"2017 january","value":3000050},{"month":"2017 february","value":6520575},],"B series":[{"month":"2017 january","value":55000},{"month":"2017 february","value":3000050},]}

const merged = Object.entries(input).reduce((r, [k, v]) => {
      v.reduce((acc, { month, value }) =>{
          acc[month] = acc[month] || { month }
          acc[month][k] = value;
          return acc
        }, r)
        
        return r;
      }, {})
      
const output = Object.values(merged)
console.log(output)