I have to remove properties from a JSON object. It's like I need to write a framework where I pass an array of location from where the fields needs to be redacted. My JSON request 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}
As I said above, this is how I captured the locations that needs to removed
let paths = ['other.tfn','tfn','other1.tfn','other2.other3.tfn'];
It remove tfn fields from almost all the places and returns
{
"name": "Rohit",
"other": [
{},
{}
],
"other1": {},
"other2": {
"other3": [
{
"tf2n": "2879872934"
},
{},
{}
]
},
"card": "sdlkjl",
"f": true}
I am curious if someone can suggest a better way to write below code
paths.forEach(function (path) {
let keys = path.split('.');
deepObjectRemove(jsonObject, keys);
});
method
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;
}
}};