Skip to content
Advertisement

How can I convert a string containing object paths and values to an object?

I want to convert strings of the form 'a|b|c', val1 and 'a|d', val2 to a nested object of the form {a: {b : {c : 'val1'}, d: 'val2'}}. I tried the following –

const path2Obj = (path, value) => {
  const obj = {};
  const pathComps = path.split('|').reverse();
  pathComps.forEach((comp, ind) => {
    if (ind) {
      obj[comp] = obj;
    } else {
      obj[comp] = value;
    }
  });
  return obj;
};
console.log(path2Obj('a|b|c', 'val1'));

but it logs <ref *1> { c: 'val1', b: [Circular *1], a: [Circular *1] }. Any ideas?

Background to my question

I am storing nested objects whose structure is not known before runtime to a redis database. Redis does not appear to support nested objects natively so I first convert the them to path / value pairs of strings and save them as hashes. This works but I need a way to convert them back to objects

Advertisement

Answer

You can basically use reduce, iterate over the path array which you created with split and then either return the value from the object if it exists, otherwise add value (new nested object or value param).

const obj = {}

const path2Obj = (path, value, obj) => {
  path.split('|').reduce((r, e, i, arr) => {
    return r[e] || (r[e] = i === arr.length - 1 ? value : {})
  }, obj)
};

path2Obj('a|b|c', 'val1', obj)
path2Obj('a|d', 'val2', obj)

console.log(obj)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement