I have a nested json object, something like this:
{
"fontweight": {
"primary": {
"weight1": {
"value": "Regular",
"type": "fontWeights"
},
"weight2": {
"value": "SemiBold",
"type": "fontWeights"
}
},
}
}
Now, I get a key and value, like this:
{
key: "fontweight.primary.weight1.value",
value: "Bold"
}
I need to update the value for the key in my nested json. How can I do so?
4
Answers
This way you can update the value when you know the key
you can have a lodash like
set
function. note that this mutates the original objectIf you happen to have lodash in your project already, then just use lodash.set
Also be carefull, usualy mutation an existing object is not a good idea when you work with frameworks. They rely on wrapper objects comparison.
No Lodash required
Assuming the nested JSON doesn’t contain the array, you can update JSON value by defining
updateValue
function which takes parametersdata
and an object as{key:'....',value:'...'}
. That function can be used to copy existing JSON to do some iteration for updating the target key with a new value like this: