改变对象javascript的结构

时间:2014-12-06 06:14:07

标签: javascript json angularjs node.js

我想更改对象javascript的结构,例如:

我有这个结构:

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

我希望将其更改为:

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

谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

试试这个:

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