Search code examples
javascriptreactjsobjectyup

Turn object path to actual object


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

Solution

  • 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)