1 回答
TA贡献1831条经验 获得超10个赞
var input = {"config_name_0":"11","mountEnv_0_5723":{"lable":"22","val":"33","type":"1"},"mountEnv_1_5723":{"lable":"44","val":"55","type":"1"},"config_name_1":"66","mountEnv_0_4268":{"lable":"77","val":"88","type":"1"},"mountEnv_1_4268":{"lable":"99","val":"00","type":"1"}};
var result = [];
var regName = /_(\d+)/;
var regMount = /_(\d+)_/;
for (var key in input) {
if (typeof input[key] == 'string') {
var index = key.match(regName)[1];
if (!result[index]) result[index] = {config_name:'', mountEnv:[]};
result[index]["config_name"] = input[key];
} else {
var index = key.match(regMount)[1];
if (!result[index]) result[index] = {config_name:'', mountEnv:[]};
result[index]["mountEnv"].push(input[key]);
}
}
这个是根据config_name_x 和 mountEnv_x_ssss中的x来确定同一个对象的数据,但是按照lz的转化完数据来看,我没看出来确切的数据对应。。
我的转化结果
[{
config_name:'11',
mountEnv:[
{"lable":"22","val":"33","type":"1"},
{"lable":"77","val":"88","type":"1"}
]
},
config_name:'66',
mountEnv:[
{"lable":"44","val":"55","type":"1"},
{"lable":"99","val":"00","type":"1"}
]
}
]
lz的是按照ssss的合并,但是前后顺序呢?
如果是可以保证前后顺序,那么可以这样
var input = {"config_name_0":"11","mountEnv_0_5723":{"lable":"22","val":"33","type":"1"},"mountEnv_1_5723":{"lable":"44","val":"55","type":"1"},"config_name_1":"66","mountEnv_0_4268":{"lable":"77","val":"88","type":"1"},"mountEnv_1_4268":{"lable":"99","val":"00","type":"1"}};
var result = [];
var regName = /_(\d+)/;
var index;
for (var key in input) {
if (typeof input[key] == 'string') {
index = key.match(regName)[1];
if (!result[index]) result[index] = {config_name:'', mountEnv:[]};
result[index]["config_name"] = input[key];
} else {
result[index]["mountEnv"].push(input[key]);
}
}
添加回答
举报