Skip to content

Create object from array JavaScript | Example code

  • by

Use the Object.assign() method to create objects from an array in JavaScript. It was introduced in ES6 and it copies the values of all enumerable own properties from one or more source objects to a target object. It has the following syntax:

Object.assign(target, ...sources)

Create object from array JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    const names = ['Alex', 'Bob', 'Johny', 'Steve'];

    const obj = Object.assign({}, names);

    console.log(obj);

  </script>

</body>
</html> 

Output:

Create object from array JavaScript

You can also use Spread Operator

const names = ['Alex', 'Bob', 'Johny', 'Steve'];


const obj = {...names};

or for loop

const names = ['Alex', 'Bob', 'Johny', 'Atta'];


const obj = {};


for (let i = 0; i < names.length; i++) {
    obj[i] = names[i];
}

Create an object from Keys and Values with 2 arrays

Not recommended iterate values and keys at the same time.

<script>

    var keys = ['key1', 'key2', 'key3'];
    var values = [
    [12,112, 1112],
    [31, 331, 3331],
    [64, 653, 6621]
    ];

    var arrayOfObjects = [];
    for(var i=0; i<values.length; i++){
      var obj = {};
      for(var j=0; j<values[i].length; j++){
       obj[keys[j]] = values[i][j];  
     }
     arrayOfObjects.push(obj);
   }

   console.log(arrayOfObjects)

</script>

Output:

0: Object { key1: 12, key2: 112, key3: 1112 }
​
1: Object { key1: 31, key2: 331, key3: 3331 }
​
2: Object { key1: 64, key2: 653, key3: 6621 }

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading