Javascript updating object from string

Issue

I have this object {country:{town:{company:{boss:{}}}}} and this string country.town.cityhouse.major, I need to updatr the object from the string, but keeping the previous properties and data.

{
  country: {
    town: {
      company: {
        boss: {}
      },
      cityhouse: {
        major: {}
      }
    }
  }
}

This is what I have so far:

function updateObj(object, path) {
            const newPath = path.split('.');
            let temp = {...object};

            for (let i = 0; i < newPath.length; i++) {
                let mid = temp[newPath[i]];
                if (mid) {
                    temp = mid;
                } else {
                    temp[newPath[i]] = {};
                }
            }

            return temp;
        }

        const obj = { country: { town: { company: { boss: {} }}}};
        const r = updateObj(obj, 'country.town.cityhouse.major');

        console.log(r);

but it responds:

{
  company: {
    boss: {}
  },
  cityhouse: {},
  major: {}
}

Any hint on this?

Solution

You can clean this up a little using logical nullish assignment(??=) and a for...of loop.

function updateObj(object, path) {
  let result = { ...object };

  let temp = result;
  for (const k of path.split('.')) {
    temp = temp[k] ??= {};
  }

  return result;
}

const obj = { country: { town: { company: { boss: {} } } } };
const r = updateObj(obj, 'country.town.cityhouse.major');

console.log(r);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recursive option

function updateObj(object, path) {

  const result = { ...object };

  const [prop, ...pathArr] = path.split('.');

  result[prop] = pathArr.length 
    ? updateObj((result[prop] ??= {}), pathArr.join('.')) 
    : (result[prop] ??= {});

  return result;
}

const obj = { country: { town: { company: { boss: {} } } } };
const r = updateObj(obj, 'country.town.cityhouse.major');

console.log(r);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answered By – pilchard

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published