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
Converting array to object by splitting the properties - JavaScript
We have an array of string literals in which each element has a dash (-). The property key is present to the left of dash and its value to the right. A sample input array would look something like this:
const arr = ["playerName-Kai Havertz", "age-21", "nationality-German", "position-CAM", "languages-German,English,Spanish", "club-Chelsea"];
We are required to write a function that splits these strings and form an object out of this array.
Let's write the code. It will loop over the array splitting each string and feeding it into the new object.
Using forEach Method
The most straightforward approach uses forEach to iterate through the array and build the object:
const arr = ["playerName-Kai Havertz", "age-21", "nationality-German",
"position-CAM", "languages-German,English,Spanish", "club-Chelsea"];
const arrayToObject = arr => {
const obj = {};
arr.forEach(string => {
const [key, value] = string.split("-");
obj[key] = value;
});
return obj;
};
console.log(arrayToObject(arr));
{
playerName: 'Kai Havertz',
age: '21',
nationality: 'German',
position: 'CAM',
languages: 'German,English,Spanish',
club: 'Chelsea'
}
Using reduce Method
A more functional approach uses reduce to accumulate the object in a single pass:
const arr = ["playerName-Kai Havertz", "age-21", "nationality-German",
"position-CAM", "languages-German,English,Spanish", "club-Chelsea"];
const arrayToObjectReduce = arr => {
return arr.reduce((obj, string) => {
const [key, value] = string.split("-");
obj[key] = value;
return obj;
}, {});
};
console.log(arrayToObjectReduce(arr));
{
playerName: 'Kai Havertz',
age: '21',
nationality: 'German',
position: 'CAM',
languages: 'German,English,Spanish',
club: 'Chelsea'
}
Using Object.fromEntries
The most concise approach uses Object.fromEntries with map:
const arr = ["playerName-Kai Havertz", "age-21", "nationality-German",
"position-CAM", "languages-German,English,Spanish", "club-Chelsea"];
const arrayToObjectEntries = arr => {
return Object.fromEntries(
arr.map(string => string.split("-"))
);
};
console.log(arrayToObjectEntries(arr));
{
playerName: 'Kai Havertz',
age: '21',
nationality: 'German',
position: 'CAM',
languages: 'German,English,Spanish',
club: 'Chelsea'
}
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
forEach |
Good | Fast | Excellent |
reduce |
Good | Fast | Excellent |
Object.fromEntries |
Excellent | Fast | ES2019+ |
Conclusion
All three methods effectively convert arrays to objects by splitting strings. Use Object.fromEntries for the cleanest code, or forEach for maximum browser compatibility.
