I am trying to change a json value with typescript with a recursive function. I know how to show all keys or values, but I don't know exactly how to change the value.
I have this json and this code:
var json = {
"a" : "hello",
"b" : "bye",
"c" : {
"d" : "test1",
"e" : "test2"
},
"f" : {
"g" : {
"h" : "test3",
"i" : "test4"
}
}
};
changeInJson(id: string, value: string, level: number, json: object): void {
level = level || 0;
for (var property in json) {
if (typeof json[property] === 'object') {
this.changeInJson(id, value, ++level, json[property]);
} else {
console.log(property);
if(property === id) {
//change value in json
console.log("Yes");
}
}
}
};
changeInJson("i", "changed", 0, json);
console.log(json);
In this example, I know the json keys but in reality I need to save somehow all the path to arrive to the key "i" and this is what I don't know how to do.
Thanks