Search code examples
javascriptjsontypescriptobject

How to remove object properties if exist on another object in Javascript / Typescript


I have this object:

{
  "id": "33343232",
  "createdAt": "2022-07-26T13:44:01.080Z",
  "updatedAt": "2022-07-26T13:45:31.000Z",
  "name": "Name Here",
  "description": "text",
}

and another object is :

specificFeatures": {
    "id": "33343232",
    "createdAt": "2022-07-26T13:44:01.087Z",
    "updatedAt": "2022-07-26T13:45:31.000Z",
    "name": "Name Here",
    "description": "text",
    "coverage": "international",
    "income": 0,
    "observationIncome": "",
}

now, I want the property keys of the specificFeatures object that are the same as the first object to be deleted.

In this example, it would be:

specificFeatures": {
    "coverage": "international",
    "income": 0,
    "observationIncome": "",
}

Can you tell me how can I do this?


Solution

  • To achieve that, you can simply iterate over the object properties, check whether the "original" object has the property, and if so, delete it from "specificFeatures" object:

    const original = {
      "id": "33343232",
      "createdAt": "2022-07-26T13:44:01.080Z",
      "updatedAt": "2022-07-26T13:45:31.000Z",
      "name": "Name Here",
      "description": "text",
    }
    
    const specificFeatures = {
      "id": "33343232",
      "createdAt": "2022-07-26T13:44:01.087Z",
      "updatedAt": "2022-07-26T13:45:31.000Z",
      "name": "Name Here",
      "description": "text",
      "coverage": "international",
      "income": 0,
      "observationIncome": "",
    }
    
    // Iterate over object keys
    Object.keys(specificFeatures).forEach(prop => {
      // Check if the "original" object has the property defined
      if (original.hasOwnProperty(prop)) {
        // Delete the property from the "specificFeatures" object
        delete specificFeatures[prop];
      }
    });
    
    console.log(specificFeatures);

    Pay attention that this way you mutate the original object, and in case you need to keep the original object as is, a new unique copy should be created. One of the possible solutions could be a combination of Object.entries() and Array.reduce() methods:

    const original = {
      "id": "33343232",
      "createdAt": "2022-07-26T13:44:01.080Z",
      "updatedAt": "2022-07-26T13:45:31.000Z",
      "name": "Name Here",
      "description": "text",
    }
    
    const specificFeatures = {
      "id": "33343232",
      "createdAt": "2022-07-26T13:44:01.087Z",
      "updatedAt": "2022-07-26T13:45:31.000Z",
      "name": "Name Here",
      "description": "text",
      "coverage": "international",
      "income": 0,
      "observationIncome": "",
    }
    
    const result = Object.entries(specificFeatures).reduce((acc, [key, val]) => {
      if (!original.hasOwnProperty(key))
        acc[key] = val;
      return acc;
    }, {});
    
    console.log(result);
    console.log('Is a different object:', result !== specificFeatures);