How to Convert an Array to an Object in JavaScript? Top 6 Ways

Photo of author

There are many objects in JavaScript that developers use worldwide. Therefore, you should know how to convert an array to an object in JavaScript. This is your best guide if you don’t understand how to do it. We will converse about the top 6 ways in detail.

The Top 6 Ways in JavaScript to convert an array to an object are:

  • Using JavaScript Object.assign() Method
  • Using JavaScript for Loop
  • Using JavaScript Object.fromEntries() Method
  • Using the Spread Operator
  • Using Array.forEach() Method
  • Using Array.reduce() Method  

Furthermore, you can convert these JavaScript objects to JSON and use it. Moreover, we will discuss these methods in depth so that you will understand how they work. Without further ado, let’s get started.

See Also: How To Use A JavaScript Variable In HTML? 5 Best Ways

This section will only discuss converting an array to an object in JavaScript.

Method 1: Using JavaScript Object.assign() Method

The first method to convert an Array to an Object in JavaScript is using the Object.assign() Method. This method is utilized to merge objects into one object. It grasps source objects and merges them into a target object. Let’s understand via an example. For instance, look at the following code:object.assign

const strobecorp = [{ keyA: ‘value2’ }, { keyB: ‘value3’ }, { keyC: ‘value4’ }];

const example = Object.assign({}, …strobecorp);

console.log(example);

Output:

{ keyA: ‘value2’, keyB: ‘value3’, keyC: ‘value4’ }

In the above example, the spread operator (…), which passes the array of objects as different arguments, is utilized. Furthermore, the empty object literal ({}) is utilized as the target object, and we get the output as a single object.

Method 2: Using JavaScript for Loop

The second method to convert an array to an object in JavaScript is using JavaScript for Loop, which developers use worldwide. In this method, we will loop over every element in the array and give it to the target object. For example, let’s look at the following code: loop

let strobecorp = [‘Java’, ‘JavaScript’, ‘HTML’, ‘CSS’];

function toObject(arr) {

    let unique = {};

    // Traverse array using loop

    for (let i = 0; i < arr.length; ++i)

        // Assign each element to object

        unique[i] = strobecorp[i];

    return unique;

}

console.log(toObject(strobecorp));

Output:

{ ‘0’: ‘Java’, ‘1’: ‘JavaScript’, ‘2’: ‘HTML’, ‘3’: ‘CSS’ }

Method 3: Using JavaScript Object.fromEntries() Method

The third method to convert an array to an object in JavaScript is to use Object.fromEntries() method. This method is handy when working with key-value pairs and converting them into a single object. The syntax for this method is:

Object.fromEntries( iterable );object fromentries

Let’s understand via an example. Look at the following code:

let example = [[‘Value1’, ‘Value2’], [‘Strobecorp’, ‘Solution’]];

let uniqueobject = Object.fromEntries(example);

 

console.log(uniqueobject);

Output:

{ Value1: ‘Value2’, Strobecorp: ‘Solution’ }

In the above example, we have an array named example, and then we have created an object with the name uniqueobject and used the syntax of this method. Now, you just have to display the object and are all set.

Method 4: Using the Spread Operator

The fourth method is using the Spread Operator. It helps a repetition to enlarge in places where 0+ arguments are anticipated. Developers commonly use it in the variable array where a 1+ value is anticipated. It allows to get a list of variables from an array. The syntax for this method is:spread operators

let variablename1 = […value];

Furthermore, let’s look at an example to understand it thoroughly. 

const example = [“Strobecorp”, “for”, “Coding”];

const uniqueobject = {…example};

console.log(uniqueobject);

Output:

{ ‘0’: ‘Strobecorp’, ‘1’: ‘for’, ‘2’: ‘Coding’ }

Method 5: Using Array.forEach() Method

The fifth method that we will discuss is the Array.forEach() method. To incorporate this method, you have to follow the steps:array for each

  • Firstly, create an empty object and declare it as a variable.
  • Secondly, utilize the Array.forEach() and repeat it over the array.
  • Now, incorporate the element as a key-value pair on every repetition, and you are all set.

Let’s look at an example to understand it thoroughly. For instance, look at the following code:

const unique = [‘John’, ‘Stuart’, ‘Chandler’, ‘Barney’]

const example = {}

unique.forEach((elem, i) => {

  example[i] = elem

})

console.log(example)

Output:

{ ‘0’: ‘John’, ‘1’: ‘Stuart’, ‘2’: ‘Chandler’, ‘3’: ‘Barney’ }

See Also: How To Convert JavaScript To TypeScript? Step-By-Step Guide

Method 6: Using Array.reduce() Method

The last method to convert an array to an object is the Array.reduce() method. This method starts a provided function for every item of the array and keeps the value in an accumulator entity. Let’s understand via an example. For instance, look at the following code:const anarray

const example = [“Harry”, “Stuart”, “Bob”]

const uniqueobject = example.reduce(function(result, item, index) {

  result[index] = item

  return result

}, {})

console.log(uniqueobject)

Output:

{ ‘0’: ‘Harry’, ‘1’: ‘Stuart’, ‘2’: ‘Bob’ }

FAQs

How to convert array-like object to array in JS?

To transform the array-like object to an array in JS, you must use the Array.from() method, which will give back an array when the array-like object is passed as an argument.

How to convert an array of objects to JSON objects in JS?

To transform an array of objects to JSON objects in JS, you must use JSON. stringify() method.

How to convert an array of objects to a string in JS?

To transform an array of objects to a string in JS, you must utilize the toString() method. This method will give back the value within the provided array as a string.

How to remove from an array of objects by value in JavaScript?

You can utilize the splice() method to eradicate an array of objects in JS.

Conclusion

In conclusion, we learned how to change an array to an object in JavaScript. The above methods are simple, and you won’t face any difficulties. Furthermore, whenever you have a key-value pair, always try to choose Object.fromEntries() Method as it is used widely. Moreover, other methods can also convert an array to an object.

For instance, JSON.parse() and JSON.stringify() can help convert and copy an array in JavaScript. You can also improve your knowledge by learning about generic array in Java or Removing A Class In JavaScript and increasing your programming skills. Don’t forget to learn the basics of declaring an empty array in JavaScript before doing other JS array functions.

See Also: How To Remove A Class In JavaScript? Top 3 Methods

Leave a Comment