大家好我想尝试将字符串数组解析为自定义结构:
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
可以更改。在我的示例中,country
和level
将始终与它们代表x
位置相同。str
数组中的字符串可以是任意长度。字符串越长越好。答案 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);
答案 1 :(得分:1)
此解决方案使用了Array.prototype.forEach
和Array.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>');