Home > database >  Turn object path to actual object
Turn object path to actual object

Time:07-11

I have a complex state value for my forms in React App. For validation, I'm using Yup. After validation, Yup is returning a string of the object path of invalid value like this: locationAvailability.availabilityPerDay.thursday.start. How can I turn this into something like this:

locationAvailability: {
  availabilityPerDay: {
     thursday: {
      start: true
   }
 }
}

CodePudding user response:

This will do probably

const object = 'locationAvailability.availabilityPerDay.thursday.start'.split('.').reduceRight((obj, prop) => {
  if (obj) {
    return {
      [prop]: obj
    }
  }
  return {
    [prop]: true
  }
}, null)

console.log(object)

  • Related