将逗号分隔的字符串转换为对象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' ]
}热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短