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
Construct objects from joining two strings JavaScript
We are required to write a JavaScript function that takes in two comma separated strings. The first string is the key string and the second string is the value string, the number of elements (commas) in both the strings will always be the same.
Our function should construct an object based on the key and value strings and map the corresponding values to the keys.
Example
const str1= '[atty_hourly_rate],[paralegal_hourly_rate],[advanced_deposit]';
const str2 = '250,150,500';
const mapStrings = (str1 = '', str2 = '') => {
const keys = str1.split(',').map( (a) => {
return a.slice(1, -1);
});
const object = str2.split(',').reduce( (r, a, i) => {
r[keys[i]] = a;
return r;
}, {});
return object;
};
console.log(mapStrings(str1, str2));
Output
{
atty_hourly_rate: '250',
paralegal_hourly_rate: '150',
advanced_deposit: '500'
}
How It Works
The function works in three steps:
-
Extract keys: Split the first string by commas and remove square brackets using
slice(1, -1) -
Build object: Use
reduce()to iterate through the second string's values and map them to corresponding keys - Return result: The accumulated object with key-value pairs
Alternative Approach Using Object.fromEntries
const mapStringsAlternative = (str1 = '', str2 = '') => {
const keys = str1.split(',').map(key => key.slice(1, -1));
const values = str2.split(',');
return Object.fromEntries(keys.map((key, index) => [key, values[index]]));
};
console.log(mapStringsAlternative(str1, str2));
{
atty_hourly_rate: '250',
paralegal_hourly_rate: '150',
advanced_deposit: '500'
}
Conclusion
Both approaches effectively construct objects from two strings by splitting, processing keys, and mapping values. The reduce() method offers more control, while Object.fromEntries() provides a cleaner, more modern solution.
Advertisements
