递归字符串解析为对象

时间:2015-08-27 12:07:57

标签: javascript parsing recursion

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

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位置相同。
  • 这需要递归方法,因为存储在str数组中的字符串可以是任意长度。字符串越长越好。

2 个答案:

答案 0 :(得分:1)

如果您的对象的最后一级是数组,这应该适合您:

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

答案 1 :(得分:1)

此解决方案使用了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>');