Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Transforming array to object JavaScript
Suppose we have an array of strings like this ?
const arr = [ 'type=A', 'day=45' ];
We are required to write a JavaScript function that takes in one such array. The function should construct an object based on this array. The object should contain a key/value pair for each string in the array.
For any string, the part before '=' becomes the key and the part after it becomes the value.
Method 1: Using for Loop
const arr = [ 'type=A', 'day=45' ];
const arrayToObject = (arr = []) => {
const obj = {};
for (let i = 0; i
{ type: 'A', day: '45' }
Method 2: Using reduce()
A more functional approach using the reduce() method:
const arr = [ 'type=A', 'day=45', 'status=active' ];
const arrayToObjectReduce = (arr = []) => {
return arr.reduce((obj, item) => {
const [key, value] = item.split('=');
obj[key] = value;
return obj;
}, {});
};
console.log(arrayToObjectReduce(arr));
{ type: 'A', day: '45', status: 'active' }
Method 3: Using Object.fromEntries()
The most concise approach using Object.fromEntries() and map():
const arr = [ 'name=John', 'age=30', 'city=Paris' ];
const arrayToObjectEntries = (arr = []) => {
return Object.fromEntries(arr.map(item => item.split('=')));
};
console.log(arrayToObjectEntries(arr));
{ name: 'John', age: '30', city: 'Paris' }
Handling Edge Cases
Here's a robust version that handles missing values and multiple equals signs:
const arr = [ 'type=A', 'url=https://example.com', 'empty=', 'noequals' ];
const arrayToObjectSafe = (arr = []) => {
const obj = {};
arr.forEach(item => {
const splitIndex = item.indexOf('=');
if (splitIndex !== -1) {
const key = item.substring(0, splitIndex);
const value = item.substring(splitIndex + 1);
obj[key] = value;
}
});
return obj;
};
console.log(arrayToObjectSafe(arr));
{ type: 'A', url: 'https://example.com', empty: '' }
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| for Loop | Good | Fastest | All browsers |
| reduce() | Excellent | Good | ES5+ |
| Object.fromEntries() | Excellent | Good | ES2019+ |
Conclusion
Use Object.fromEntries() with map() for the cleanest code in modern environments. For maximum compatibility, stick with the traditional for loop approach.
Advertisements
