简体   繁体   中英

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'
      }
    }
  }
}

I wrote a reciursive function and a wrapper to call it.

 const obj = { name: 'root/branch/subbranch/leaf', value: 'my-value' } const recursiveNest = (result, value, arr, index = 0) => { const path = arr[index] if (index < arr.length - 1) { result[path] = {} index +=1; recursiveNest(result[path], value, arr, index) } else { result[arr[index]] = value; } }; const createNestedObject = (obj, splitBy) => { let result = {} recursiveNest(result, obj.value, obj.name.split(splitBy)) return result; } console.log(createNestedObject(obj, '/'));

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)

Lodash provides setWith(object, path, value, [customizer]) :

 const obj = { name: 'root/branch/subbranch/leaf', value: 'my-value' } console.log(_.setWith({}, obj.name.split('/'), obj.value, _.stubObject))
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM