John John - 3 months ago 12
Javascript Question

Converting a js object into a string map (the opposite from the usual string to object)

I know there are plenty of methods to take a dot separated string and map it to a js object, and there are hundred of questions with answers on here about that.

But i need to do the reverse:

To convert this:

let object = {
parts: {
x: {
create: () => {
alert(321);
},
update: () => {
alert(321);
}
},
y: {
create: () => {
alert(321);
},
update: () => {
alert(321);
}
}
}
}


To this:

{
'parts.x.create': () => {
alert(321);
},
'parts.x.update': () => {
alert(321);
},
'parts.y.create': () => {
alert(321);
},
'parts.y.update': () => {
alert(321);
}
}


I feel like i am starting to reinvent the wheel when i start to write the code for this. Has anyone else done or seen this before?

Answer Source

This should do the trick:

let object = {
  parts: {
    x: {
      create: () => {
        alert(321);
      },
      update: () => {
        alert(321);
      }
    },
    y: {
      create: () => {
        alert(321);
      },
      update: () => {
        alert(321);
      }
    }
  }
};

let convert = (value, keys = '', obj = {}) => {
  if (typeof value === 'object') {
    for (let index in value) {
      convert(value[index], (keys && keys + '.') + index, obj);
    }
  } else {
    obj[keys] = value;
  }
  return obj;
}

let newObject = convert(object);
console.log(newObject);