0

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

Gunjan Kumar
  • 667
  • 3
  • 8
  • 27
  • 1
    Deleting a property is the same in Node.JS as in browser javascript. You cannot delete headers the same way that you can delete properties of an object. – quicVO Mar 15 '21 at 01:45
  • 1
    The language in nodejs is just Javascript. In fact, it's the same Javascript engine that runs in Chrome. So, you remove a property from an object with `delete` just like everywhere in Javascript. For request headers, it totally depends upon what API you're using and how things are structured. You'd have to show that code for us to advise there. – jfriend00 Mar 15 '21 at 01:47
  • @quicVO - I know it is JavaScript and already put sample code how I handled it. Trying to see any native Nodejs function ( native I mean e.g. fs, require etc.) – Gunjan Kumar Mar 17 '21 at 03:00

1 Answers1

1

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320