我有一个 javascript 对象定义为(在我无法控制的其他地方创建)。
var config = {
a: 2
}
config['b[1]'] = 9;
config['b[2]'] = 8;
config['c[test]'] = 3;
我想把它转换成类似的东西。 (对于键 1,我的意思是 config['b']['1'] = 9 )
var transformed = {
a: 2,
b: { 1: 9, 2: 8},
c: { test: 3}
}
如何轻松做到这一点?如果有帮助,我会使用 lodash。
最佳答案
您可以使用 for() 循环遍历对象键并使用匹配函数获取必要的新键。 希望这有帮助
var config = {
a: 2
};
config['b[1]'] = 9;
config['c[test]'] = 3;
var key, match, obj;
for(key in config) {
match = key.match(/(.+)\[(.+)\]/);
if(match) { // for example key is 'b[1]'
obj = config[match[1]] || {}; // <= Update create new object or use filled
obj[match[2]] = config[key]; // add new property (match[2] => '1') to new object
config[match[1]] = obj; // add new property (match[1] => 'b') to config
delete config[key]; // remove composite key
}
}
console.dir(config);
关于javascript - 如何将格式化为数组变量的字符串转换为javascript对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34684324/