在 JavaScript 中將逗號分隔字串轉換為物件中的單獨陣列


假設我們有一個這樣的字串 −

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' ]
}

更新於:2020 年 11 月 23 日

574 次瀏覽

開啟您的事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.