1

here I am creating a javascript object like this:

let obj = { "how": "fetch", "method": "get", "url": "^http://.*"};

And i want to remove the property url to end up with new obj as follows:

let obj = { "how": "fetch", "method": "get"};

What is the best way to do it?

Questions
  • 23
  • 2
  • Please spent some time researching if your question has already been answered here, there is an almost identical question – empiric Nov 20 '20 at 12:30

4 Answers4

2

You can do this in one line.

delete obj.url
1

If you prefer functional JavaScript, you can use object destructuring:

const { url, ...objWithoutUrl } = obj;

This has the performance disadvantage of creating a new object, but the stability advantage of not mutating the original object. When you pass objects between functions, it can lead to undesired effects when a function mutates the object with delete.

code-gorilla
  • 2,231
  • 1
  • 6
  • 21
0
delete obj.url;
// or you can try with
delete obj['url'];
0

Another way to do it is set a variable with the key that you want.

const someName = "objectKey";

and then use the delete method

delete array[objectKey];

in your case it would be like that:

const key = "url";
delete obj[key];