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