I have JSON object
var a = { a: { b: 10, c: 10 } }
I want a method that can change JSON object dynamically. Suppose when i supply object , string and a value to method it should return updated JSON object
change(a, 'a.b', 30)
change method is as follows:-
function change(obj, str, val) {
const newObject = str.split('.').reverse()
.reduce((a,p,i) => {
if(i===0) a[p] = val
else { let b = {}; b[p] = a; a = b}
return a;
},{})
return { ...obj, ...newObject }
}
it should return
{ a: { b : 30, c: 10 } }
without modifying other json fields but it is currently returning
{ a: { b : 30 } }