Cho chuỗi 'dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james'. Tách thành đối tượng: key là phần trước dấu '/', value là mảng các phần còn lại.
Ví dụ
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));
Kết quả
{ dress: [ 'cotton', 'black', 'leather', 'red', 'fabric' ], houses: [ 'restaurant', 'small', 'school', 'big' ], person: [ 'james' ] }