สมมุติว่าเรามีสตริงแบบนี้ −
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' ]
}