1

I want to change the structure of an object javascript, for example:

I have this structure :

obj = {
        "email": "abc@site.com", 
        "societe.name": "xyz"
      }

and I want to change it to :

obj = {
        "email": "abc@site.com",
        "societe": {
            "name": "xyz"
        }
      }

thank's for help.

1 Answers1

2

Try this:

var obj = {
    "email": "abc@site.com",
        "societe.name": "xyz"
};

var newObj = {};
var keys = Object.keys(obj);

for (var i = 0; i < keys.length ; i++) {
    var key = keys[i];

    // you can change this to '.name' if you want to be specific      
    if (key.indexOf('.') > -1) {
        var splitted = key.split('.');
        var innerObj = {};
        innerObj[splitted[1]] = obj[key];
        newObj[splitted[0]] = innerObj;
    } else {
        newObj[key] = obj[key];
    }
}

console.log(newObj);

JSFIDDLE.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99