Skip to content

Instantly share code, notes, and snippets.

@mhamzas
Created June 23, 2022 07:21
Show Gist options
  • Save mhamzas/b042511ce294439a04c4a7dd8fd6bf0f to your computer and use it in GitHub Desktop.
Save mhamzas/b042511ce294439a04c4a7dd8fd6bf0f to your computer and use it in GitHub Desktop.
JSON - Search for keys in nested object and delete them
/* https://stackoverflow.com/questions/68678126/search-for-keys-in-nested-object-and-delete-them */
function cleanData(data, deleteKeys) {
// There is nothing to be done if `data` is not an object,
// but for example "user01" or "MALE".
if (typeof data != "object") return;
if (!data) return; // null object
for (const key in data) {
if (deleteKeys.includes(key)) {
delete data[key];
} else {
// If the key is not deleted from the current `data` object,
// the value should be check for black-listed keys.
cleanData(data[key], deleteKeys);
}
}
}
const data = {
"details": [{
"userId": "user01",
"documents": [{
"document": {
"id": "doc_pp_01",
"type": "pp",
"number": "222333444",
"personName": {
"first": "JAMES",
"middle": "JOHNIE",
"last": "SMITH"
},
"nationality": "AL",
"dateOfBirth": "1990-01-01",
"issuingCountry": "AL",
"expiryDate": "2025-01-01",
"gender": "MALE"
}
}]
}],
"criteria": {
"id:": "AB1234",
"fullName": "James Johnie Smith"
}
};
cleanData(data, ["details", "fullName"]);
console.log(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment