다음과 같은 문자열이 있다고 가정해 보겠습니다. -
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' ]
}