简体   繁体   中英

Merge multiple arrays of objects based on property conditions

I have the following 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
   },
   {
      ...
   }
]

I'd like to combine them into one array which looks something like this:

{
   "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
},
{
   ...
},

The series can be 2, 3 or more, where the Main series is the principal and I receive it in position 2 or 3. And the year/month is the value that is repeated.

You could use a nested reduce like this. Create an accumulator with unique month as key and keep updating it

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM