Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string that formatted as array variable into javascript object?

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.

like image 675
jay.m Avatar asked Sep 08 '26 07:09

jay.m


1 Answers

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);
like image 148
yurzui Avatar answered Sep 10 '26 19:09

yurzui