递归字符串解析为对象 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/2 6:04:17
我们需要编写一个 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 可以更改。在我的示例中,国家/地区和级别将始终相同,因为它们代表 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"
]
}
}
}
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

