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
Converting a comma separated string to separate arrays within an object JavaScript
When working with comma-separated strings containing hierarchical data, we often need to parse them into structured objects. This article shows how to convert a string like 'dress/cotton/black, dress/leather/red' into an organized object with arrays.
The Problem
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 need to create a JavaScript function that converts this into an object where each category becomes a key, and all related values are grouped into arrays:
const output = {
dress: ["cotton", "black", "leather", "red", "fabric"],
houses: ["restaurant", "small", "school", "big"],
person: ["james"]
};
Solution Using Array Methods
Here's how we can parse the string and build the object structure:
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));
{
dress: [ 'cotton', 'black', 'leather', 'red', 'fabric' ],
houses: [ 'restaurant', 'small', 'school', 'big' ],
person: [ 'james' ]
}
How It Works
The solution follows these steps:
-
Split by commas:
str.split(', ')creates an array of individual items -
Split by slashes:
el.split('/')separates each item into parts -
Extract key:
values.shift()removes and returns the first element as the key -
Merge values:
(result[key] || []).concat(values)combines new values with existing ones
Alternative Using reduce()
Here's a more functional approach using reduce():
const str = 'dress/cotton/black, dress/leather/red, dress/fabric';
const buildObjectReduce = (str = '') => {
return str.split(', ').reduce((acc, item) => {
const [key, ...values] = item.split('/');
acc[key] = (acc[key] || []).concat(values);
return acc;
}, {});
};
console.log(buildObjectReduce(str));
{
dress: [ 'cotton', 'black', 'leather', 'red', 'fabric' ]
}
Handling Edge Cases
To make the function more robust, we can handle empty strings and malformed data:
const buildObjectSafe = (str = '') => {
if (!str.trim()) return {};
const result = {};
const items = str.split(',').map(s => s.trim()).filter(s => s);
items.forEach(item => {
const parts = item.split('/').filter(part => part.trim());
if (parts.length > 0) {
const [key, ...values] = parts;
result[key] = (result[key] || []).concat(values);
}
});
return result;
};
console.log(buildObjectSafe('dress/cotton, , houses/school'));
{
dress: [ 'cotton' ],
houses: [ 'school' ]
}
Conclusion
Converting comma-separated hierarchical strings into structured objects is straightforward using split(), shift(), and concat(). The key is to first split by delimiters, then group values by their category keys for organized data access.
