Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading