Search code examples
javascriptstringobjectsplittransform

JavaScript: Create object with nested properties from string split by specific character


How to use the name property in this object:

const obj = {
  name: 'root/branch/subbranch/leaf',
  value: 'my-value'
}

To create an object with the following format:

{
  root: {
    branch: {
      subbranch: {
        leaf: 'my-value'
      }
    }
  }
}

Solution

  • You could do this using split and reduce

    const obj = {
      name: 'root/branch/subbranch/leaf',
      value: 'my-value'
    }
    
    
    let newObj = {}
    const parts = obj.name.split('/')
    parts.reduce((prev, curr, i) => (
      Object.assign(
        prev, 
        {[curr]: i === parts.length - 1 ? obj.value : Object(prev[curr])}
      ), 
      prev[curr]
    ), newObj)
    
    console.log(newObj)