I have a complex javascript object containing multiple nested arrays and maps. I would like to delete every field of the object with a given name.
For example:
{
"myObj":{
"name":"John",
"deleteMe":30,
"cars":{
"car1":"Ford",
"car2":"BMW",
"deleteMe":"Fiat",
"wheels":{
"one":"Round",
"two":"Square",
"deleteMe":"Fiat"
}
}
}
}
How could I delete every field with a name/key of "deleteMe". I do not know the structure of the object ahead of time.
You need to either find the key in the object or recursively descend into any value that is itself an object:
function deleteMe(obj, match) {
delete obj[match];
for (let v of Object.values(obj)) {
if (v instanceof Object) {
deleteMe(v, match);
}
}
}
const myObj = {
"name":"John",
"deleteMe":30,
"cars":{
"car1":"Ford",
"car2":"BMW",
"deleteMe":"Fiat",
"wheels":{
"one":"Round",
"two":"Square",
"deleteMe":"Fiat"
}
}
}
const recursiveRemoveKey = (object, deleteKey) => {
delete object[deleteKey];
Object.values(object).forEach((val) => {
if (typeof val !== 'object') return;
recursiveRemoveKey(val, deleteKey);
})
}
recursiveRemoveKey(myObj, 'deleteMe');
console.log(myObj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With