递归字符串解析为对象

Recursive string parsing into object

本文关键字:对象 字符串 递归      更新时间:2023-09-26

大家好,我正在尝试将字符串数组解析为自定义结构:

var str = [
"country.UK.level.1",
"country.UK.level.2",
"country.US.level.1",
"country.UK.level.3"
];

变成:

var ordered = {
   "country": [
      {"UK" : {"level" : ["1", "2", "3"]}},
      {"US" : {"level" : ["1","2"]}}
   ]
}

指出:

  • 存储在str数组中的字符串不会被排序,代码应该健壮。
  • 字符串将遵循x.y.x.y...模式,其中x对于该数组是唯一的,y可以改变。在我的示例中,countrylevel将始终与它们表示x pos相同。
  • 这需要递归方法,因为存储在str数组中的字符串可以是任意长度。字符串越长嵌套越深。

如果你的对象的最后一层是一个数组,这应该对你有用:

var str = [
"country.UK.level.1",
"country.UK.level.2",
"country.US.level.1",
"country.UK.level.3"
];
var obj = {};
str.forEach(function(str){
    var curr = obj;
    var splitted = str.split('.');
    var last = splitted.pop();
    var beforeLast = splitted.pop();
    splitted.forEach(function(sub){
        if(!curr.hasOwnProperty(sub))
        {
            curr[sub] = {};
        }
        curr = curr[sub];
    });
    if(!curr[beforeLast]){
        curr[beforeLast] = [];
    }
    curr[beforeLast].push(last);
})
console.log(obj);

JSFIDDLE .

此解决方案使用了Array.prototype.forEachArray.prototype.reduce

var str = [
        "country.UK.level.1",
        "country.UK.level.2",
        "country.US.level.1",
        "country.UK.level.3"
    ],
    ordered = {};
str.forEach(function (a) {
    var aa = a.split('.'),
        val = aa.pop(),
        last = aa.length - 1;
    aa.reduce(function (obj, pro, i) {
        if (!(pro in obj)) {
            obj[pro] = i === last ? [] : {};
        }
        return obj[pro];
    }, ordered).push(val);
});
document.write('<pre>' + JSON.stringify(ordered, 0, 4) + '</pre>');