Search code examples
javascriptbackbone.js

Expand a dict key with dot as another dict


I have a dictionary looks like

var p = {
     'name' : "John",
     'personal.phone' : "123456",
     'office.phone.number' : "321654",
     'office.phone.extn': "4"
}

I want to convert the dict with doted keys expanded like

{
     'name' : "John",
     'personal' : {
                       'phone' : "123456",
                  }
     'office' :   {
                        'phone' : { 
                                      number : "321654",
                                      extn : "4" 
                                  }
}

A function I wrote for expanding a single key. but its not exiting the loop

function expdictkey(str,v) {
    str = str.split(".").reverse();
    var p = {}
    for (var i = 0; i < str.length; i++)
    {
        p[str[i]] = p
        console.log(p)
    }
    return p;
}

expdictkey("phone.number.extn","4")

I am getting values from a from in the form of first dict, I want to convert it like second dict and put it in a model and save it. using backbone.js, and django rest server. in server the model is in the form of second dict.


Solution

  • Here you go:

    var p = {
      'name': "John",
      'personal.phone': "123456",
      'office.phone.number': "321654",
      'office.phone.extn': "4"
    }
    
    
    
    
    function unwrap() {
      var obj = {};
      for (var index in p) {
        var keys = index.split('.');
        var value = p[index];
        var ref = obj;
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          if (keys.length - 1 === i) {
            ref[key] = value;
          } else {
            if (ref[key] === undefined) {
              ref[key] = {}
            }
            ref = ref[key]
          }
        }
      }
      return obj;
    }
    
    unwrap(p);