在 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.