After receiving a response from a web service, I need to replace certain values in the response with custom values that I have defined.
One possible approach is to create a tree traverser to identify the specific values and replace them with the custom values.
The original response looks like this:
[
{
"name": "n1",
"value": "v1",
"children": [
{
"name": "n2",
"value": "v2"
}
]
},
{
"name": "n3",
"value": "v3"
}
]
Here is my custom mapping:
const map = {
"v1": "v11",
"v2": "v22",
"v3": "v33"
};
What I wish to achieve is:
[
{
"name": "n1",
"value": "v11",
"children": [
{
"name": "n2",
"value": "v22"
}
]
},
{
"name": "n3",
"value": "v33"
}
]
I am considering the idea of converting the response to a string and then using a custom regular expression to replace the values based on my map.
- Would this method be more efficient than using a tree traverser?
- If so, what would be the best way to implement it?
It would look something like this:
originalString.replace(regexp, function (replacement))