Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

Convert an array of objects to a single object in JavaScript

Programming Bytes

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 array 
for(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);
Convert an array of objects into a single object

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 the finalObj object.
  • After the end of the loop, all the objects of the array are converted into a single object.

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring