Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to create an object from a dot separated string?

I ran into this potential scenario that I posed to a few of my employees as a test question. I can think of a couple ways to solve this problem, but neither of them are very pretty. I was wondering what solutions might be best for this as well as any optimization tips. Here's the question:

Given some arbitrary string "mystr" in dot notation (e.g. mystr = "node1.node2.node3.node4") at any length, write a function called "expand" that will create each of these items as a new node layer in a js object. For the example above, it should output the following, given that my object name is "blah":

blah: { node1: { node2: { node3: { node4: {}}}}}

From the function call:

mystr = "node1.node2.node3.node4";
blah = {};
expand(blah,mystr);

Alternately, if easier, the function could be created to set a variable as a returned value:

mystr = "node1.node2.node3.node4";
blah = expand(mystr);

Extra credit: have an optional function parameter that will set the value of the last node. So, if I called my function "expand" and called it like so: expand(blah, mystr, "value"), the output should give the same as before but with node4 = "value" instead of {}.

like image 639
runfaj Avatar asked Jul 16 '15 20:07

runfaj


1 Answers

In ES6 you can do it like this:

function expand(str, val = {}) {
  return str.split('.').reduceRight((acc, currentValue) => {
    return { [currentValue]: acc }
  }, val)
}

const blah = expand('a.b.c.d', 'last value')
like image 166
Dzmitry Bachko Avatar answered Oct 21 '22 05:10

Dzmitry Bachko