I would like to add some data to a nested javascript object, however I do not know how much of the object tree already exists. I want to add the structure if it is not there, but also keep the same information if it is there tagged with some other default data.
Ideally I don’t want to use a third party library for this.
In my example I have the following object structure, there will be an endless combination of these available, so it needs to generate the structure for me if it does not already exist.
{
level1: {
level2: {
level3: {
property1: 'test'
}
}
}
}
I want to be able give this some values, create the structure – if the structure is there, add some default values and if not create the structure with defaults.
I have the following, which does the job, but it looks very messy to me, I was wondering if there was a better way to achieve this?
const updateNestedObject = (obj, level1, level2, level3, defaultProps) => {
if (obj && obj[level1] && obj[level1][level2] && obj[level1][level2][level3]) {
obj[level1][level2][level3] = { ...defaultProps, ...obj[level1][level2][level3] }
} else if (obj && obj[level1] && obj[level1][level2] && !obj[level1][level2][level3]) {
obj[level1][level2][level3] = defaultProps
} else if (obj && obj[level1] && !obj[level1][level2]) {
obj[level1][level2] = { [level3]: defaultProps }
} else if (obj && !obj[level1]) {
obj[level1] = { [level2]: { [level3]: defaultProps } }
} else {
obj = { [level1]: { [level2]: { [level3]: defaultProps } } }
}
return obj
}