1

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

I have this structure :

obj = {
        "email": "[email protected]", 
        "societe.name": "xyz"
      }

and I want to change it to :

obj = {
        "email": "[email protected]",
        "societe": {
            "name": "xyz"
        }
      }

thank's for help.

9
  • this doesn't tell us anything about how it is implemented, or why you can't just change it to what you show. nor does it show any research effort. Commented Dec 6, 2014 at 6:16
  • obj[societe] = {};``obj[societe][name] = obj["societe.name"]; delete obj["societe.name"]; Commented Dec 6, 2014 at 6:17
  • 1
    It's pretty obvious what requirement the example is illustrating. There's no need to berate OP for not putting it into words. Commented Dec 6, 2014 at 6:19
  • yes you can change it Commented Dec 6, 2014 at 6:21
  • 2
    @BatScream I want to thank you a lot, thank's a lot man, it's been three days since I tried without any result. thank you Commented Dec 6, 2014 at 6:26

1 Answer 1

2

Try this:

var obj = {
    "email": "[email protected]",
        "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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.