JavaScript 中解析字串為物件的遞迴方法
我們要求編寫一個 JavaScript 函式,該函式接受一個字串陣列並返回一個與字串相對應的物件。
例如 −
如果該陣列為 −
const arr = [ "country.UK.level.1", "country.UK.level.2", "country.US.level.1", "country.UK.level.3" ];
則輸出應為 −
const output = {
"country": [
{"UK" : {"level" : ["1", "2", "3"]}},
{"US" : {"level" : ["1","2"]}}
]
}
條件
儲存在 str 陣列中的字串不會被排序,並且該程式碼應對此保持魯棒性。
字串將遵循 x.y.x.y... 模式,其中 x 將對該陣列是唯一的,而 y 可以改變。在我的示例中,country 和 level 始終相同,因為它們表示 x 座標。
這需要遞迴方法,因為儲存在 str 陣列中的字串的長度可以任意。字串越長,巢狀的深度就越大。
示例
程式碼如下 −
const arr = [
"country.UK.level.1",
"country.UK.level.2",
"country.US.level.1",
"country.UK.level.3"
];
const stringToObject = arr => {
const obj = {};
arr.forEach(str => {
let curr = obj;
let splitted = str.split('.');
let last = splitted.pop();
let beforeLast = splitted.pop();
splitted.forEach( sub => {
if(!curr.hasOwnProperty(sub)){
curr[sub] = {};
};
curr = curr[sub];
});
if(!curr[beforeLast]){
curr[beforeLast] = [];
};
curr[beforeLast].push(last);
});
return obj;
};
console.log(JSON.stringify(stringToObject(arr), undefined, 4));輸出
這會在控制檯中產生以下輸出 −
{
"country": {
"UK": {
"level": [
"1",
"2",
"3"
]
},
"US": {
"level": [
"1"
]
}
}
}
廣告
資料結構
網路技術
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP