
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ] }
- Related Questions & Answers
- Converting array of arrays into an object in JavaScript
- How to convert comma separated text in div into separate lines with JavaScript?
- Converting two arrays into a JSON object in JavaScript
- How to convert a comma separated String into an ArrayList in Java?
- How to use a comma-separated string in an `IN ()` in MySQL?
- MySQL query to search between comma separated values within one field?
- Convert a List of String to a comma separated String in Java
- Convert a Set of String to a comma separated String in Java
- Converting a JavaScript object to an array of values - JavaScript
- Java Program to Convert a List of String to Comma Separated String
- JavaScript Converting array of objects into object of arrays
- How to sum a comma separated string (string with numbers) in MySQL?
- Converting string to an array in JavaScript
- How can I search within a table of comma-separated values in MySQL?
- Convert String into comma separated List in Java
Advertisements