I am currently working on a task that involves removing properties from a JSON object. I need to create a system where I can specify an array of locations from which the fields should be redacted. The JSON request I am dealing with looks like this:
{
"name": "Rohit",
"other": [{
"tfn": "2879872934"
}, {
"tfn": "3545345345"
}],
"other1": {
"tfn": "3545345345"
},
"other2": {
"other3": [{
"tf2n": "2879872934"
}, {
"tfn": "3545345345"
}, {
"tfn": "2342342234"
}]
},
"card": "sdlkjl",
"tfn": "2879872934",
"f": true}
To achieve this, I have identified the specific paths that need to be removed:
let paths = ['other.tfn','tfn','other1.tfn','other2.other3.tfn'];
After applying the removal process, the updated JSON object will look like this:
{
"name": "Rohit",
"other": [
{},
{}
],
"other1": {},
"other2": {
"other3": [
{
"tf2n": "2879872934"
},
{},
{}
]
},
"card": "sdlkjl",
"f": true}
I feel there might be a more efficient way to implement the code below:
paths.forEach(function (path) {
let keys = path.split('.');
deepObjectRemove(jsonObject, keys);
});
This is the method used for removal:
var deepObjectRemove = function(obj, path_to_key){
if(path_to_key.length === 1){
delete obj[path_to_key[0]];
return true;
}else{
if(obj[path_to_key[0]] && Array.isArray(obj[path_to_key[0]])) {
obj[path_to_key[0]].forEach(function (value) {
deepObjectRemove(value, path_to_key.slice(1));
});
//return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
}else if(obj[path_to_key[0]]){
deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
}else{
return false;
}
}};