Keywords: JavaScript | array to object | Object.fromEntries | key-value pairs | data processing
Abstract: This article explains how to convert an array of key-value tuples into an object in JavaScript for easy key-based access. It focuses on the Object.fromEntries() method and compares other traditional approaches.
Introduction
In JavaScript development, we often encounter arrays containing key-value tuples. For example, data may be stored as [['key1', 'value1'], ['key2', 'value2']]. However, arrays do not support direct element access by key; attempting arr['key'] does not return the expected value. To address this, it is necessary to convert the array into an object, enabling convenient key-based data access.
Modern Solution: Using Object.fromEntries()
Introduced in ECMAScript 2019 (ES10), the Object.fromEntries() method provides a concise way to convert an array of key-value pairs into an object. Its syntax is Object.fromEntries(iterable), where iterable is an iterable object containing arrays of key-value pairs.
const array = [['cardType', 'iDEBIT'], ['txnAmount', '17.64']];
const obj = Object.fromEntries(array);
console.log(obj.txnAmount); // Output: 17.64
This method is widely supported in modern browsers and Node.js environments and is recommended for use in compatible projects.
Traditional and Alternative Methods
If Object.fromEntries() is not available, the following methods can be considered:
- forEach loop: Iterate over the array and manually construct the object.
var obj = {};
array.forEach(function(data) {
obj[data[0]] = data[1];
});
const obj = array.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
Object.assign(...array.map(([key, val]) => ({[key]: val})));
const map = new Map(array);
console.log(map.get('txnDate'));
Comparison and Best Practices
Object.fromEntries() is the most direct and efficient method, offering concise code. forEach and reduce are suitable for learning functional programming or scenarios requiring custom logic. The Map object provides additional features, such as keys of any type, but uses different access methods (e.g., get()).
When choosing a method, consider code readability, performance requirements, and environment compatibility. For new projects, using Object.fromEntries() is recommended; in older environments, polyfills or fallback to traditional methods can be used.
Conclusion
Through the methods introduced in this article, developers can easily convert arrays of key-value tuples into objects in JavaScript, enabling key-based data access. Mastering these techniques helps improve data processing efficiency and code quality.