Search code examples
javascriptnode.jscomparisonjavascript-objects

Omit an object with certain deep values from another object


I'm trying to omit req.body data, when updating a resource in a collection, with only the fields that are null or '' for that existing resource in the collection.

But this could also be generic, that's why the title is more generic.

Anyways, imagine the following:

We have a user in our database with the following data:

{
  "firstName": "John",
  "lastName": "Doe",
  "address": {
    "Address1": "Random street 1",
    "City": "",
    "Country": null
  },
  "email": ""
}

The user is trying to update the existing resource with the following data:

{
  "firstName": "Mark",
  "address": {
    "Address1": "Random street 2",
    "City": "NY",
    "Country": "USA"
  },
  "email": "[email protected]"
}

Updated object should like like this:

{
  "firstName": "John", // Unchanged because propety value already exists
  "lastName": "Doe",
  "address": {
    "Address1": "Random street 1", // Unchanged because propety value already exists
    "City": "NY", // Updated because existing value is empty ("")
    "Country": "USA" // Updated because existing value is null
  },
  "email": "[email protected]" // Updated because existing value is empty ("")
}

I'm using mongoose, but I would rather implement this on the basic javascript object level


Solution

  • I am not aware of any library but below is the working example using recursion.

    var oldObj = {
      "firstName": "John",
      "lastName": "Doe",
      "address": {
        "Address1": "Random street 1",
        "City": "",
        "Country": null
      },
      "email": ""
    }
    
    var newObj = {
      "firstName": "Mark",
      "address": {
        "Address1": "Random street 2",
        "City": "NY",
        "Country": "USA"
      },
      "email": "[email protected]"
    }
    
    updateObject(oldObj, newObj);
    
    
    function updateObject(oldObj, newObj) {
      Object.keys(oldObj).forEach( key => {
        if (oldObj[key] && typeof oldObj[key] === 'object') {
          updateObject(oldObj[key], newObj[key]);
        } else {
          oldObj[key] = oldObj[key] || newObj[key];
        }
      });
    }
    
    console.log("Modified Obj: ", oldObj);

    Hope this may help you.