将带有分隔键的对象转换为嵌套对象

时间:2013-09-18 05:48:23

标签: javascript node.js

我有一个带分隔键的对象,我想将此对象转换为嵌套对象。任何人都知道在javascript或节点中快速做的事情吗?

例如:

    {
      'login': 'my login',
      'work.title': 'my title',
      'work.phone.mobile': '123',
      'work.phone.work': '456'
    }

转换为

   {
      login: 'my login',
      work: {
        title: 'my title',
        phone: {
          mobile: '123',
          work: '456'
        }
      }
    }

2 个答案:

答案 0 :(得分:3)

你试试这个

function toObj(str)
{
    var output = {};
    for(var key in str)
    {
        var nodes = key.split('.'), dest = output;
        if(nodes.length < 1) continue;
        for(var i = 0; i < (nodes.length - 1); ++ i)
        {
            var node = nodes[i];
            dest = (dest[node] === undefined) ? (dest[node] = {}) : dest[node];
        }
        dest[nodes[nodes.length - 1]] = str[key];
    }
    return output;
}

通话功能

toObj({
    'login': 'my login',
    'work.title' : 'my title',
    'work.phone.mobile' : '123',
    'work.phone.work' : '456'
});

DEMO.

答案 1 :(得分:3)

第一个参数是你想要解除的对象,第二个参数是修改obj还是创建一个新对象。第二个参数是可选的,默认为false

function unflatten(obj, modify){
    var i, j, keys, ref, result = modify ? obj : {};
    for(i in obj){
        for(keys = i.split('.'), ref = result, j = 0; j < keys.length - 1; j++)
            ref = (ref[keys[j]] = ref[keys[j]] || {});
        ref[keys[j]] = obj[i];
        if(modify && j)
            delete obj[i];
    }
    return result;
}