Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript delete nested object properties by name [duplicate]

Tags:

javascript

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.

like image 805
F_SO_K Avatar asked Nov 01 '25 11:11

F_SO_K


2 Answers

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);
    }
  }
}
like image 95
Alnitak Avatar answered Nov 03 '25 04:11

Alnitak


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);
like image 39
Abror Abdullaev Avatar answered Nov 03 '25 02:11

Abror Abdullaev