สมมติว่ามีสตริงดังนี้:
const str = 'dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james';
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงดังกล่าว ฟังก์ชันควรเตรียมออบเจ็กต์ของอาร์เรย์ดังนี้:
const output = {
dress: ["cotton","leather","black","red","fabric"],
houses: ["restaurant","school","small","big"],
person: ["james"]
};
ตัวอย่าง
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' ]
}