Convert array of objects to an object of arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of objects like this −

const nights = [
   { "2016-06-25": 32, "2016-06-26": 151, "2016-06-27": null },
   { "2016-06-24": null, "2016-06-25": null, "2016-06-26": null },
   { "2016-06-26": 11, "2016-06-27": 31, "2016-06-28": 31 },
];

We are required to write a JavaScript function that takes in one such array and constructs an object of arrays based on object keys.

Therefore, the output for the above array should look like −

const output = {
"2016-06-24": [null],
"2016-06-25": [32, null],
"2016-06-26": [151, null, 11],
"2016-06-27": [null, 31],
"2016-06-28": [31]
};

Example

The code for this will be:

const nights = [
   { "2016-06-25": 32, "2016-06-26": 151, "2016-06-27": null },
   { "2016-06-24": null, "2016-06-25": null, "2016-06-26": null },
   { "2016-06-26": 11, "2016-06-27": 31, "2016-06-28": 31 },
];
const arrayToObject = (arr = []) => {
   const res = {};
   for(let i = 0; i < arr.length; i++){
      const keys = Object.keys(arr[i]);
      for(let j = 0; j < keys.length; j++){
         if(res.hasOwnProperty(keys[j])){
            res[keys[j]].push(arr[i][keys[j]]);
         }
         else{
            res[keys[j]] = [arr[i][keys[j]]];
         }
      }
   };
   return res;
};
console.log(arrayToObject(nights));

Output

And the output in the console will be −

{
   '2016-06-25': [ 32, null ],
   '2016-06-26': [ 151, null, 11 ],
   '2016-06-27': [ null, 31 ],
   '2016-06-24': [ null ],
   '2016-06-28': [ 31 ]
}
raja
Published on 21-Nov-2020 15:04:30
Advertisements