Skip to content Skip to sidebar Skip to footer

Build Nested Object In Javascript

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.ge

Solution 1:

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 objectvar parent = obj;

    while(part = parts.shift()) {

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

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

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

    //finally return the populated objectreturn parent;

}

Solution 2:

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);

Post a Comment for "Build Nested Object In Javascript"