Flat a JavaScript array of objects into an object

JavascriptWeb DevelopmentObject Oriented Programming

To flat a JavaScript array of objects into an object, we created a function that takes array of object as only argument. It returns a flattened object with key append by its index. The time complexity is O(mn) where n is the size of array and m is the number of properties in each object. However, its space complexity is O(n) where n is the size of actual array.

Example

//code to flatten array of objects into an object
//example array of objects
const notes = [{
   title: 'Hello world',
   id: 1
}, {
   title: 'Grab a coffee',
   id: 2
}, {
   title: 'Start coding',
   id: 3
}, {
   title: 'Have lunch',
   id: 4
}, {
   title: 'Have dinner',
   id: 5
}, {
   title: 'Go to bed',
   id: 6
}, ];
const returnFlattenObject = (arr) => {
   const flatObject = {};
   for(let i=0; i<arr.length; i++){
      for(const property in arr[i]){
         flatObject[`${property}_${i}`] = arr[i][property];
      }
   };
   return flatObject;
}
console.log(returnFlattenObject(notes));

Output

Following is the output in console −

[object Object] {
   id_0: 1,
   id_1: 2,
   id_2: 3,
   id_3: 4,
   id_4: 5,
   id_5: 6,
   title_0: "Hello world",
   title_1: "Grab a coffee",
   title_2: "Start coding",
   title_3: "Have lunch",
   title_4: "Have dinner",
   title_5: "Go to bed"
}
raja
Published on 18-Aug-2020 10:23:35
Advertisements