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:

  1. Extract keys: Split the first string by commas and remove square brackets using slice(1, -1)
  2. Build object: Use reduce() to iterate through the second string's values and map them to corresponding keys
  3. 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.

Updated on: 2026-03-15T23:19:00+05:30

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements