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.


const str1= '[atty_hourly_rate],
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));


And the output in the console will be −

   atty_hourly_rate: '250', paralegal_hourly_rate: '150', advanced_deposit: '500'

Updated on: 23-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started