0

Given a JS string: var s = "deep.deeper.deepest", how can I convert this into object like this: deep: {deeper: {deepest: {}}}

dovstone
  • 124
  • 11

2 Answers2

2
 const dottedToObj = (str, orig = {}) => (str.split(".").reduce((obj, key) => obj[key] = {}, orig), orig);

Just reduce the array of strings (splitted the original string) into a chain of objects. Or a bit less functional:

 function dottedToObj(str){
  const root = {};
  var acc = root;
  for(const key of str.split(".")){
    acc = acc[key] = {};
  }
  return root;
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

A simple loop should work for this, just move through each dotted property while moving down one level in the object:

const s = "deep.deeper.deepest";

function convertToObject(str) {
  const result = {};
  
  let inner = result;
  for (const key of s.split(".")) {
    // Give the object a child with this key
    inner[key] = {};
  
    // Set the current object to that child.
    inner = inner[key]
  }
  
  // Return the original
  return result;
}

console.log(convertToObject(s))
CRice
  • 29,968
  • 4
  • 57
  • 70