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.
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);
finalObj
. This will be our final merged object.Object.assign()
method to merge all the properties of the current array object element with the finalObj
object.