How to Remove a Property from a JavaScript Object

How do I remove a property from a JavaScript object?

To remove a property from an object (mutating the object), you can do it like this:

delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];

Demo

var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
delete myObject.regex;

console.log(myObject);

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key];

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

let animals = {
'Cow': 'Moo',
'Cat': 'Meow',
'Dog': 'Bark'
};

delete animals.Cow;
delete animals['Dog'];

console.log(animals);

How to delete Javascript object property?

newObj inherits from obj.

You can delete the property by accessing the parent object:

delete Object.getPrototypeOf(newObj).name;

(which changes the parent object)

You can also shadow it, by setting the value to undefined (for example):

newObj.name = undefined;

But you can't remove the property on newObj without deleting it from the parent object as the prototype is looked up the prototype chain until it is found.

how to delete a property from an object in Typescript without the operand of a 'delete' operator must be optional error?

Typescript warns you about breaking the contract (the object won't have the required property anymore). One of the possible ways would be omitting the property when you cloning the object:

const myEvent = {
coordinate: 1,
foo: 'foo',
bar: true
};

const { coordinate, ...eventData } = myEvent;
// eventData is of type { foo: string; bar: boolean; }

Playground



Operands for delete must be optional.
When using the delete operator in strictNullChecks, the operand must be any, unknown, never, or be optional (in that it contains undefined in the type). Otherwise, use of the delete operator is an error.

Docs

Delete a property from JavaScript object without using delete operator

Using ES6 Deconstructing Operator you can do a

ler arr = [{id:1, name: foo}, {id:2, name: bar}]
arr.map({id, ...item} => {
return item
})

Consider you want to remove id property the above code will remove the id property and returns the object containing the name property.

Removing object properties with Lodash

Get a list of properties from model using _.keys(), and use _.pick() to extract the properties from credentials to a new object:

var model = {
fname:null,
lname:null
};

var credentials = {
fname:"xyz",
lname:"abc",
age:23
};

var result = _.pick(credentials, _.keys(model));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

How to remove the first property of an object?

First of all: Javascript (ES5) don't guarantee property order. There are still browsers running on ES5 (IE11 ahem, although they keep property order partially) so depending on your environment, I recommend you to follow this rule.

That's a really really important point.

Now, after you understood why you shouldn't do that, I'll explain a way to remove the first property (whatever first is in your current environment).

You can do it two ways. The most performant way in IE11 and Firefox is this one:

for (var i in obj) {
delete obj[i];
break;
}

And also you can do:

delete obj[Object.keys(obj)[0]];

Which is less performant on IE and Firefox but better on Chrome (performance test below):

function newList() {

var objs = [];

var props = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ";

for (var i = 0; i < 200000; i++) {

var obj = {};

for (var ii = 0; ii < props.length; ii++) {

obj[props[ii]] = ii;

}

objs.push(obj);

}

return objs;

}

var objs = newList();

console.time("Object.keys()");

for (var i = 0; i < objs.length; i++) {

delete objs[i][Object.keys(objs[i])[0]];

}

console.timeEnd("Object.keys()");

objs = newList();

console.time("for...in");

for (i = 0; i < objs.length; i++) {

for (var j in objs[i]) {

delete objs[i][j];

break;

}

}

console.timeEnd("for...in");

Delete property and its values in all the object

You could use a recursive algorithm :

function del_entries(key, obj) {
if (obj.hasOwnProperty(key)) {
delete obj[key];
}

// Or with Object.hasOwn, not fully supported by old browsers but more up to date
/*
if (Object.hasOwn(obj, key)) {
delete obj[key]
}
*/

Object.values(obj).forEach(o=> del_entries(key, o))
}

const MyGraph = {
a: { b: 5, c: 2 },
b: { a: 5, c: 7, d: 8 },
c: { a: 2, b: 7, d: 4, e: 8 },
};

del_entries("a", MyGraph);

console.log(MyGraph)

How to delete property from spread operator?

You could use Rest syntax in Object Destructuring to get all the properties except drugName to a rest variable like this:

const transformedResponse = [{

drugName: 'HYDROCODONE-HOMATROPINE MBR',

drugStrength: '5MG-1.5MG',

drugForm: 'TABLET',

brand: false

},

{

drugName: 'HYDROCODONE ABC',

drugStrength: '10MG',

drugForm: 'SYRUP',

brand: true

}]

const output = transformedResponse.map(({ drugName, ...rest }) => rest)

console.log(output)


Related Topics



Leave a reply



Submit