Recursive split while delimiter exists in the string and then create an object

Advertisements

Suppose I have the following string: plan.details.notes (Note: this string can have more/less sub nodes) and I have a value that should be set to it once it has been destructured, ie. "hello".

Here’s what I want to achieve:

{
  plan {
    details {
      notes: "hello"
    }
  }
}

I currently have the following code:

function recursiveSplitIntoObject(string, delimiter, value) {
  if (!string) return {}

  let stringToSplit = string
  const returnObj = {}

  while (stringToSplit.indexOf(delimiter) >= 0) {
    const split = string.split(delimiter)
    returnObj[split[0]] = { [split[1]]: value }
    stringToSplit = split[1]
  }

  console.log(returnObj)
}

I’m not sure how to assign a dynamic object inside the [split[1]]: value. I maybe close but I can’t figure it out. Can anyone lead me to the right direction? Thanks!

>Solution :

Remove the last key, process all other keys and finally assign the last key:

function recursiveSplitIntoObject(string, delimiter, value) {
    let start = {},
        curr = start,
        keys = string.split(delimiter),
        last = keys.pop()

    for (let key of keys)
        curr = (curr[key] = {})
    
    curr[last] = value

    return start
}

console.log(
    recursiveSplitIntoObject('plan.details.notes', '.', 'hello'))

Leave a Reply Cancel reply