In JavaScript, you can create an object from an array using several methods, such as Object fromEntries(), reduce(), and a loop. This tutorial will provide examples and explanations for creating an object from an array of key-value pairs in JavaScript.
JavaScript creates the object from an array example
A simple example code creates an object from an array using several methods.
Object fromEntries() method
This method takes an iterable of key-value pairs and returns a new object whose properties are given by those pairs.
const arr = [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']];
const obj = Object.fromEntries(arr);
console.log(obj); // { key1: 'value1', key2: 'value2', key3: 'value3' }
reduce() method
It will convert an array of key-value pairs to an object.
const arr = [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']];
const obj = arr.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
console.log(obj); // { key1: 'value1', key2: 'value2', key3: 'value3' }
Using a loop
Use a loop to iterate over the array and add the key-value pairs to an object.
<!DOCTYPE html>
<html>
<body>
<script>
const arr = [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']];
const obj = {};
for (let [key, value] of arr) {
obj[key] = value;
}
console.log(obj);
console.log(typeof(obj))
</script>
</body>
</html>
Output:
Comment if you have any doubts or suggestions on this Js creating 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