Search code examples
javascriptarraysjavascript-objects

Map Object with Array as Values to Array of Objects


I have the following object with arrays as values:

{
  A: [{date: 21.01.2020, number: 4000}, {date: 22.01.2020, number: 3800}],

  B: [{date: 21.01.2020, number: 4000}, {date: 22.01.2020, number: 3800}],

  C: [{date: 21.01.2020, number: 4000}, {date: 22.01.2020, number: 3800}]
}

My goal is to translate this data into an array of objects:

[
 {
  "date": "21.01.2020",
  "A": 4000,
  "B": 4000,
  "C": 4000
 },
 {
  "date": "22.01.2020",
  "A": 3800,
  "B": 3800,
  "C": 3800
 }
]

I understand that I can get the individual keys (A,B,C) from the current object by using:

Object.keys(...)

My problem is that I don't want to map through the current object itself, but I need to map through the values of the current object, the array containing the data that I need (the initial object contains 3 key value pairs, the goal is to transform this into 2 objects).

What would be the best way to map through the values of the object and to create the array?


Solution

  • You can use this approach by using only forEach. On this method, I first group the data by date and then return the values of the object into an array.

    const data = {
    	A: [{date: '21.01.2020', number: 4000}, {date: '22.01.2020', number: 3800}],
    	B: [{date: '21.01.2020', number: 4000}, {date: '22.01.2020', number: 3800}],
    	C: [{date: '21.01.2020', number: 4000}, {date: '22.01.2020', number: 3800}]
    };
    
    const res = {};
    
    // Group the data object by the date and make another object
    Object.keys(data).forEach(key => {
        data[key].forEach(value => {
    	if (typeof res[value.date] == 'undefined') {
    	    res[value.date] = {};
    	}
    	res[value.date].date = value.date;
    	res[value.date][key] = value.number;
        });
    });
    
    // Finally make the object as array of object
    const output = Object.values(res);
    console.log(output);
    .as-console-wrapper { max-height: 100% !important; top: 0; }