-2

I trying to build a nested object, I'll try to make myself clear.

I have this json structure:

 {
      "origin.geo.country": "USA",
      "origin.geo.state": "NY",
      "origin.geo.zip": 4444,
      "user.name": "Michael",
      "user.surname": "Jordan"  
}

And I need a function that outputs something like this:

{
     origin: {
         geo: {
             country: "USA",
             state: "NY",
             zip: 4444
         }
     },
     user: {
         name: "Michael",
         surname: "Jordan"
     }
 }

I know i have to use recursion to achieve this, but I'm not able to code it. Can you guys help me with this?

Thanks.

Miguel Pinto
  • 447
  • 1
  • 3
  • 15

2 Answers2

2

So guys,

@Ben Beck answer helped me.

I just need to make some minor changes to the function:

function (path,value,obj) {

    var parts = path.split("."), part;

    //reference the parent object
    var parent = obj;

    while(part = parts.shift()) {

        // here I check if the property already exists
        if( !obj.hasOwnProperty(part) ) obj[part] = {};

        // if is the last index i set the prop value
        if(parts.length === 0) obj[part] = value;

        obj = obj[part]; // update "pointer"
    }

    //finally return the populated object
    return parent;

}
Miguel Pinto
  • 447
  • 1
  • 3
  • 15
0

You could reach the desired solution using e.g. Array#reduce.

const o = {
  "origin.geo.country": "USA",
  "origin.geo.state": "NY",
  "origin.geo.zip": 4444,
  "user.name": "Michael",
  "user.surname": "Jordan",
};

const r = Object.keys(o).reduce((s, a) => {
  const t = a.split('.');
  const k = t[0];
  const v = t[t.length - 1];
  k in s ? s[k][v] = o[a] : s[k] = Object.assign({}, { [v]: o[a] });
  return s;
}, {});

console.log(r);
kind user
  • 40,029
  • 7
  • 67
  • 77