简体   繁体   中英

change structure of an object javascript

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM