Converting a comma separated string to separate arrays within an object JavaScript


Suppose, we have a string like this −

const str = 'dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james';

We are required to write a JavaScript function that takes in one such string. The function should then prepare an object of arrays like this −

const output = {
   dress = ["cotton","leather","black","red","fabric"];
   houses = ["restaurant","school","small","big"];
   person = ["james"];
};

Example

const str = 'dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james';
const buildObject = (str = '') => {
   const result = {};
   const strArr = str.split(', ');
   strArr.forEach(el => {
      const values = el.split('/');
      const key = values.shift();
      result[key] = (result[key] || []).concat(values);
   });
   return result;
};
console.log(buildObject(str));

Output

And the output in the console will be −

{
   dress: [ 'cotton', 'black', 'leather', 'red', 'fabric' ],
   houses: [ 'restaurant', 'small', 'school', 'big' ],
   person: [ 'james' ]
}

Updated on: 23-Nov-2020

519 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements