I am trying to deeply assign a value in an object. For example:
const errors = {}
if(errorOnSpecificField) {
// TypeError: Cannot read property 'subSubCategory' of undefined(…)
errors.subCategory.subSubCategory.fieldWithError = 'Error Message'
}
Right now, without lodash, I can do:
const errors = {}
if(errorOnSpecificField) {
errors.subCategory = errors.SubCategory || {}
errors.subCategory.subSubCategory = errors.SubCategory.subSubCategory || {}
errors.subCategory.subSubCategory.fieldWithError = 'Error Message'
}
With lodash, I can do this:
const errors = {}
if(errorOnSpecificField) {
_.set(errors, 'subCategory.subSubCategory.fieldWithError', 'Error Message');
}
I am trying to avoid using a third party library. Is there a more elegant solution, especially now that es2015 has object destructuring. The inverse operation is easy:
let {subCategory : {subSubCategory: {fieldWithError}}} = errors
What is an elegant solution to deep object assignment? Thanks!