Search code examples
javascriptnode.jsobjectcopydeep-copy

Nodejs Delete fields or property from an object


Normally in Javascript we do -

var someObj = {};
someObj.name="somename";
delete someObj.name;

But in NodeJS what is right way to delete Object field/property.

Use Case :In your NodeJs Rest API e.g. Express server Rest API - You have received 20 header fields and internally you have to call another service which only need 18 (out of 20) headers. You can create totally new header object and set each of them by your code /loop etc. One approach is create a shallow copy of existing/incoming header object and remove/delete extra 2 fields.

I have tried above sample code and it works fine but not sure if that is recommended approach or something natively available in NodeJs itself.

More example for headers Your express server req.headers

let headers=req.headers;
//assuming it has content-type:"application/json" , uuid:"some-test-uuid"
delete headers.uuid 
//now after delete it has content-type:"application/json" only


Solution

  • If your current code doesn't result in any problems that you can see with a realistic connection load, it's probably perfectly fine.

    If you had to process lots and lots of requests, a potential issue is that delete can be slow in some engines like V8 - and Node runs V8. You may find a slight performance improvement if you

    • set the properties you don't need to undefined or null, without actually deleting them from the object (make sure the service can handle this format), or

    • using object rest syntax to collect the properties you do need, eg:

      function handleRequest(someObjWithLotsOfProperties) {
        const { name, userId, ...rest } = someObjWithLotsOfProperties;
        callOtherAPI(rest);
      }
      

      to call the other API with all properties except name and userId.

    They're options to consider if the current approach becomes visibly problematic.