I have a javascript object defined as (which created elsewhere that I have no control over).
var config = {
a: 2
}
config['b[1]'] = 9;
config['b[2]'] = 8;
config['c[test]'] = 3;
I would like to convert it to something like. ( for key 1, I mean config['b']['1'] = 9 )
var transformed = {
a: 2,
b: { 1: 9, 2: 8},
c: { test: 3}
}
How do I do that easily? I use lodash if it helps.
You can use a for() loop to go through objects keys and use match function to obtain the necessary new keys. Hope this helps
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With