Convert an array of objects to a single object in JavaScript
Overview
We loop the array and use the Object.assign() method to convert an array of objects to a single object. This merges each object into a single resultant object.
The Object.assign() method also merges the properties of one or more objects into a single object.
Example
The code below demonstrates how to convert an array of objects into a single object:
let arr = [{apple: "π"}, {orange: "π"}, {strawberry: "π"}];let finalObj = {};console.log("The array is \n", arr);// loop elements of the arrayfor(let i = 0; i < arr.length; i++ ) {Object.assign(finalObj, arr[i]);}console.log("\nAfter converting array of objects to single object");console.log(finalObj);
Explanation
- Line 1: We create an array of objects.
- Line 2: We create a new object,
finalObj. This will be our final merged object. - Lines 6β8: We loop the elements of the array.
- Line 7: We use the
Object.assign()method to merge all the properties of the current array object element with thefinalObjobject. - After the end of the loop, all the objects of the array are converted into a single object.