Can we assign array to object in javascript?

You could use an accumulator aka reduce.

['a','b','c'].reduce(function(result, item, index, array) {
  result[index] = item; //a, b, c
  return result;
}, {}) //watch out the empty {}, which is passed as "result"

Pass an empty object {} as a starting point; then "augment" that object incrementally. At the end of the iterations, result will be {"0": "a", "1": "b", "2": "c"}

If your array is a set of key-value pair objects:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item) {
  var key = Object.keys(item)[0]; //first property: a, b, c
  result[key] = item[key];
  return result;
}, {});

will produce: {a: 1, b: 2, c: 3}

For the sake of completeness, reduceRight allows you to iterate over your array in reverse order:

[{ a: 1},{ b: 2},{ c: 3}].reduceRight(/* same implementation as above */)

will produce: {c:3, b:2, a:1}

Your accumulator can be of any type for you specific purpose. For example in order to swap the key and value of your object in an array, pass []:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
  var key = Object.keys(item)[0]; //first property: a, b, c
  var value = item[key];
  var obj = {};
  obj[value] = key;
  result.push(obj);
  return result;
}, []); //an empty array

will produce: [{1: "a"}, {2: "b"}, {3: "c"}]

Unlike map, reduce may not be used as a 1-1 mapping. You have full control over the items you want to include or exclude. Therefore reduce allows you to achieve what filter does, which makes reduce very versatile:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
  if(index !== 0) { //skip the first item
    result.push(item);
  }
  return result;
}, []); //an empty array

will produce: [{2: "b"}, {3: "c"}]

Caution: reduce and Object.key are part of ECMA 5th edition; you should provide a polyfill for browsers that don't support them (notably IE8).

See a default implementation by Mozilla.

Convert an Array to Object using JavaScript #

Use the Object.assign() method to convert an array to an object, e.g. const obj = Object.assign({}, arr). The Object.assign method takes a target and source objects as parameters, applies the properties from the sources to the target and returns the result.

Copied!

const arr = ['zero', 'one', 'two']; const obj1 = Object.assign({}, arr); console.log(obj1); // 👉️ {0: 'zero', 1: 'one', 2: 'two'}

We passed the following 2 parameters to the Object.assign method:

  1. target object - the object to which we apply the sources' properties
  2. source object(s) - objects containing the properties we want to apply

The method returns an object where the keys are the array indexes and the values are the array elements.

Convert an Array to Object using forEach() #

To convert an array to an object:

  1. Declare a variable and set it to an empty object.
  2. Use the forEach method to iterate over the array.
  3. On each iteration, add the element as a key/value pair to the object.

Copied!

const arr = ['zero', 'one', 'two']; const obj3 = {}; arr.forEach((element, index) => { obj3['key' + index] = element; }); // 👇️️ {'key0': 'zero', 'key1': 'one', 'key2': 'two'} console.log(obj3);

The function we passed to the Array.forEach method gets called with each element in the array.

The method also gives us access to the index of the current iteration.

This approach is a bit more manual, however it allows you to name the keys of the new object.

Convert an Array to Object using Spread #

Use the spread syntax (...) to convert an array to an object, e.g. const obj = {...arr}. The spread syntax will unpack the values of the array into a new object, where the indexes of the array are the object's keys and the elements in the array - the object's values.

Copied!

const arr = ['zero', 'one', 'two']; const obj2 = {...arr}; console.log(obj2); // 👉️ {0: 'zero', 1: 'one', 2: 'two'}

We used the spread syntax (...) to unpack the array elements into an object.

The (...) syntax can be used with any iterable, such as an array, string, Set, etc.

Similarly to the first approach, the indexes of the array become the object's keys and the elements become the object's values.

Convert an Array to Object using reduce #

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result.

Copied!

const arr = ['zero', 'one', 'two']; const obj4 = arr.reduce((accumulator, value, index) => { return {...accumulator, [key + index]: value}; }, {}); // 👇️️ {'key0': 'zero', 'key1': 'one', 'key2': 'two'} console.log(obj4);

The function we passed to the Array.reduce method gets called with each element in the array.

We set an empty object as the initial value for the accumulator variable.

On each iteration, we assign a new key-value pair to the object and return the value for the accumulator variable.

This approach also allows you to assign any key name that your use case requires. We used the string "key" + the index, however you can adjust this as needed.

Convert an Array to Object using Object.fromEntries #

To convert an array of key-value pairs to an object, pass the array to the Object.fromEntries() method, e.g. const obj = Object.fromEntries(arr). The Object.fromEntries method transforms an array of key-value pairs into an object and returns the result.

Copied!

const arr2 = [ ['name', 'Tom'], ['age', 30], ]; const obj5 = Object.fromEntries(arr2); console.log(obj5); // 👉️ {name: 'Tom', age: 30}

Notice that we have a two-dimensional array this time. The nested arrays contain 2 elements each - a key and a value.

The Object.fromEntries method takes an iterable such as an array or a Map as a parameter and returns a new object that is constructed by the entries of the iterable.

Conclusion #

There are multiple ways to convert an array to an object:

  1. Using Object.assign() - Object.assign({}, ['a', 'b', 'c']).
  2. Using the spread syntax - {...['a', 'b', 'c']}.
  3. Using the reduce() method.
  4. Using the Object.fromEntries() method.

Further Reading #

  • Convert an Array's Values to Object Keys in JavaScript
  • Convert all Values in a Set to Lowercase in JavaScript

Can we assign array to object?

You can convert an array into an object using one of these three methods: The Object. assign() function. Loop over the array and construct a new object.

How do you assign an array value to an object?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.

How do you declare array of objects in JavaScript?

To initialize an array of objects, use the Array() constructor to create an array filled with N empty elements and use a for loop to iterate over the array assigning each element to an object. Copied! const arr2 = new Array(2); for (let i = 0; i < arr2.

How do you map an array to an object?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.