在 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' ]
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP