Reputation: 98260
Given an object:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
How do I remove the property regex
to end up with the following myObject
?
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
Upvotes: 7562
Views: 3324016
Reputation: 5115
The following is a simple typescript safe function which returns a clone of a supplied object with an arbitrary number of properties removed:
function removePropertiesFromObject<T, K extends keyof T>(obj: T, ...properties: K[]) {
const result = { ...obj };
for (const prop of properties) {
delete result[prop];
}
return result as Omit<T, K>;
}
Usage:
const original = { a: 1, b: 2, c: 3 };
const clone = removePropertiesFromObject(original, "a", "b");
console.log(clone); // { c: 3 }
Explanation:
The function has an object parameter (of type T) and a rest parameter for the properties to be removed (each of type K which is restricted to be a key of type T). When multiple properties are passed then K will be the union type of the properties provided. In the example above K will be of type "a" | "b"
.
The function then first clones the original object and subsequently removes the properties provided. This clone is still of type T though, so a cast is applied to re-align the type with the created object. In the example above this would lead to Omit<T, "a" | "b">
leaving "c" as the only resulting property of the return type.
Upvotes: 0
Reputation: 181
If anyone needs a solution with typescript, I leave my contribution, greetings
/* eslint-disable @typescript-eslint/no-unused-vars */
export const removePropertyFromObject = <T, K extends keyof T>(obj: T, prop: K): Omit<T, K> => {
const { [prop]: _, ...rest } = obj;
return rest;
};
interface IMyObject {
ircEvent: string;
method: string;
regex: string;
}
const obj: IMyObject = {
ircEvent: 'PRIVMSG',
method: 'newURI',
regex: '^http://.*',
};
const newObj = removePropertyFromObject(obj, 'method');
console.log(newObj);
Upvotes: 6
Reputation: 546373
To remove a property from an object (mutating the object), you can do it by using the delete
keyword, 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);
For anyone interested in reading more about it, Stack Overflow user kangax has written an incredibly in-depth blog post about the delete
statement on their blog, Understanding delete. It is highly recommended.
If you'd like a new object with all the keys of the original except some, you could use destructuring.
Demo
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
// assign the key regex to the variable _ indicating it will be unused
const { regex: _, ...newObj } = myObject;
console.log(newObj); // has no 'regex' key
console.log(myObject); // remains unchanged
Upvotes: 9948
Reputation: 18116
There are a few of ways of removing properties from an object:
1) Remove using the dot property accessor (mutable)
const myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*",
};
delete myObject.regex;
console.log(myObject);
2. Remove using square brackets property accessor (mutable)
const myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*",
};
delete myObject['regex'];
console.log(myObject);
// or
const name = 'ircEvent';
delete myObject[name];
console.log(myObject);
3) Removing without altering the original object is possible by using object destructuring and rest syntax (immutable)
const myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*",
};
const { regex, ...myObjectRest} = myObject;
console.log(myObjectRest);
Upvotes: 37
Reputation: 20892
const key = 'a';
const { [key]: foo, ...rest } = { a: 1, b: 2, c: 3 };
console.log(foo); // 1
console.log(rest); // { b: 2, c: 3 }
* foo
will be a new variable with the value of a
(which is 1).
There are a few common ways to remove a property from an object (or to address it as such).
Each one has its own pros and cons (check this performance comparison):
It is readable and short. However, it might not be the best choice if you are operating on a large number of objects, as its performance is not optimized.
delete obj[key];
In certain conditions, it can be handy. It is more than two times faster than a delete
operator, but both key and value are not deleted and can be iterated (or skipped).
obj[key] = null;
obj[key] = false;
obj[key] = undefined;
This ES6
operator allows us to return a brand new object, excluding any properties, without mutating the existing object. The downside is that it has the worst performance out of the above and is not recommended for use when you need to remove many properties at a time.
{ [key]: val, ...rest } = obj;
Upvotes: 279
Reputation: 78677
var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
delete myObject.regex;
console.log(myObject.regex); // logs: undefined
This works in Firefox and Internet Explorer, and I think it works in all others.
Upvotes: 322
Reputation: 117
We can easily remove any property of an object by using the delete operator.
const object = {
prop1: 10,
prop2: 20,
prop3: 30,
"test prop": "This is test props"
}
console.log(object); // will print all 4 props
delete object.prop1;
delete object["test prop"];
console.log(object); // it will print only prop2 and prop3
See docs : MDN
Upvotes: 3
Reputation: 683
This is how I do.
const obj = {
name: 'John',
age: 30,
gender: 'male'
};
delete obj.age;
console.log(obj); // { name: 'John', gender: 'male' }
Upvotes: 1
Reputation: 2191
As of 2023, you can do it in just one line:
delete myObject.regex;
OR
delete myObject["regex"];
(For instance if you have an object obj
with a property called key-one
, you cannot do obj.key-one
, so here comes obj["key-one"]
).
Upvotes: 5
Reputation: 12961
The term you have used in your question title, Remove a property from a JavaScript object, can be interpreted in some different ways. The one is to remove it for whole the memory and the list of object keys or the other is just to remove it from your object. As it has been mentioned in some other answers, the delete
keyword is the main part. Let's say you have your object like:
myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
If you do:
console.log(Object.keys(myJSONObject));
the result would be:
["ircEvent", "method", "regex"]
You can delete that specific key from your object keys like:
delete myJSONObject["regex"];
Then your objects key using Object.keys(myJSONObject)
would be:
["ircEvent", "method"]
But the point is if you care about memory and you want to whole the object gets removed from the memory, it is recommended to set it to null before you delete the key:
myJSONObject["regex"] = null;
delete myJSONObject["regex"];
The other important point here is to be careful about your other references to the same object. For instance, if you create a variable like:
var regex = myJSONObject["regex"];
Or add it as a new pointer to another object like:
var myOtherObject = {};
myOtherObject["regex"] = myJSONObject["regex"];
Then even if you remove it from your object myJSONObject
, that specific object won't get deleted from the memory, since the regex
variable and myOtherObject["regex"]
still have their values. Then how could we remove the object from the memory for sure?
The answer would be to delete all the references you have in your code, pointed to that very object and also not use var
statements to create new references to that object. This last point regarding var
statements, is one of the most crucial issues that we are usually faced with, because using var
statements would prevent the created object from getting removed.
Which means in this case you won't be able to remove that object because you have created the regex
variable via a var
statement, and if you do:
delete regex; //False
The result would be false
, which means that your delete statement haven't been executed as you expected. But if you had not created that variable before, and you only had myOtherObject["regex"]
as your last existing reference, you could have done this just by removing it like:
myOtherObject["regex"] = null;
delete myOtherObject["regex"];
In other words, a JavaScript object is eligible to be killed as soon as there is no reference left in your code pointed to that object.
Update:
Thanks to @AgentME:
Setting a property to null before deleting it doesn't accomplish anything (unless the object has been sealed by Object.seal and the delete fails. That's not usually the case unless you specifically try).
To get more information on Object.seal
: Object.seal()
Upvotes: 82
Reputation: 1095
Short answer
var obj = {
data: 1,
anotherData: 'sample'
}
delete obj.data //this removes data from the obj
You are left with
var obj = {
anotherData: 'sample'
}
Upvotes: 1
Reputation: 9279
Dan's assertion that 'delete' is very slow and the benchmark he posted were doubted. So I carried out the test myself in Chrome 59. It does seem that 'delete' is about 30 times slower:
var iterationsTotal = 10000000; // 10 million
var o;
var t1 = Date.now(),t2;
for (let i=0; i<iterationsTotal; i++) {
o = {a:1,b:2,c:3,d:4,e:5};
delete o.a; delete o.b; delete o.c; delete o.d; delete o.e;
}
console.log ((t2=Date.now())-t1); // 6135
for (let i=0; i<iterationsTotal; i++) {
o = {a:1,b:2,c:3,d:4,e:5};
o.a = o.b = o.c = o.d = o.e = undefined;
}
console.log (Date.now()-t2); // 205
Note that I purposely carried out more than one 'delete' operations in one loop cycle to minimize the effect caused by the other operations.
Upvotes: 13
Reputation: 1005
In JavaScript, there are 2 common ways to remove properties from an object.
The first mutable approach is to use the delete object.property
operator.
The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax:
const {property, ...rest} = object
Upvotes: 1
Reputation: 104870
Using delete method is the best way to do that, as per MDN description, the delete operator removes a property from an object. So you can simply write:
delete myObject.regex;
// OR
delete myObject['regex'];
The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. However, it is important to consider the following scenarios:
- If the property which you are trying to delete does not exist, delete will not have any effect and will return true
- If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).
- Any property declared with var cannot be deleted from the global scope or from a function's scope.
- As such, delete cannot delete any functions in the global scope (whether this is part of a function definition or a function (expression).
- Functions which are part of an object (apart from the
global scope) can be deleted with delete.
- Any property declared with let or const cannot be deleted from the scope within which they were defined. Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().
The following snippet gives another simple example:
var Employee = {
age: 28,
name: 'Alireza',
designation: 'developer'
}
console.log(delete Employee.name); // returns true
console.log(delete Employee.age); // returns true
// When trying to delete a property that does
// not exist, true is returned
console.log(delete Employee.salary); // returns true
For more info about and seeing more examples visit the link below:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
Upvotes: 41
Reputation: 4111
To clone an object without a property:
For example:
let object = { a: 1, b: 2, c: 3 };
And we need to delete a
.
With an explicit prop key:
const { a, ...rest } = object;
object = rest;
With a variable prop key:
const propKey = 'a';
const { [propKey]: propValue, ...rest } = object;
object = rest;
A cool arrow function 😎:
const removeProperty = (propKey, { [propKey]: propValue, ...rest }) => rest;
object = removeProperty('a', object);
For multiple properties
const removeProperties = (object, ...keys) => (keys.length ? removeProperties(removeProperty(keys.pop(), object), ...keys) : object);
Usage
object = removeProperties(object, 'a', 'b') // result => { c: 3 }
Or
const propsToRemove = ['a', 'b']
object = removeProperties(object, ...propsToRemove) // result => { c: 3 }
Upvotes: 125
Reputation: 8998
The delete
operator is used to remove properties from objects.
const obj = { foo: "bar" };
delete obj.foo;
obj.hasOwnProperty("foo"); // false
Note that, for arrays, this is not the same as removing an element. To remove an element from an array, use Array#splice
or Array#pop
. For example:
arr; // [0, 1, 2, 3, 4]
arr.splice(3,1); // 3
arr; // [0, 1, 2, 4]
Strictly speaking, it's impossible to truly delete anything in JavaScript. The delete
operator neither deletes objects nor frees memory. Rather, it sets its operand to undefined
and manipulates the parent object so that the member is gone.
let parent = {
member: { str: "Hello" }
};
let secondref = parent.member;
delete parent.member;
parent.member; // undefined
secondref; // { str: "Hello" }
The object is not deleted. Only the reference is. Memory is only freed by the garbage collector when all references to an object are removed.
Another important caveat is that the delete
operator will not reorganize structures for you, which has results that can seem counterintuitive. Deleting an array index, for example, will leave a "hole" in it.
let array = [0, 1, 2, 3]; // [0, 1, 2, 3]
delete array[2]; // [0, 1, empty, 3]
This is because arrays are objects. So indices are the same as keys.
let fauxarray = {0: 1, 1: 2, length: 2};
fauxarray.__proto__ = [].__proto__;
fauxarray.push(3);
fauxarray; // [1, 2, 3]
Array.isArray(fauxarray); // false
Array.isArray([1, 2, 3]); // true
Different built-in functions in JavaScript handle arrays with holes in them differently.
for..in
statements will skip the empty index completely.
A naive for
loop will yield undefined
for the value at the index.
Any method using Symbol.iterator
will return undefined
for the value at the index.
forEach
, map
and reduce
will simply skip the missing index, but will not remove it
Example:
let array = [1, 2, 3]; // [1,2,3]
delete array[1]; // [1, empty, 3]
array.map(x => 0); // [0, empty, 0]
So, the delete
operator should not be used for the common use-case of removing elements from an array. Arrays have a dedicated methods for removing elements and reallocating memory: Array#splice()
and Array#pop
.
Array#splice
mutates the array, and returns any removed indices. deleteCount
elements are removed from index start
, and item1, item2... itemN
are inserted into the array from index start
. If deleteCount
is omitted then elements from startIndex are removed to the end of the array.
let a = [0,1,2,3,4]
a.splice(2,2) // returns the removed elements [2,3]
// ...and `a` is now [0,1,4]
There is also a similarly named, but different, function on Array.prototype
: Array#slice
.
Array#slice
is non-destructive, and returns a new array containing the indicated indices from start
to end
. If end
is left unspecified, it defaults to the end of the array. If end
is positive, it specifies the zero-based non-inclusive index to stop at. If end
is negative it, it specifies the index to stop at by counting back from the end of the array (eg. -1 will omit the final index). If end <= start
, the result is an empty array.
let a = [0,1,2,3,4]
let slices = [
a.slice(0,2),
a.slice(2,2),
a.slice(2,3),
a.slice(2,5) ]
// a [0,1,2,3,4]
// slices[0] [0 1]- - -
// slices[1] - - - - -
// slices[2] - -[3]- -
// slices[3] - -[2 4 5]
Array#pop
removes the last element from an array, and returns that element. This operation changes the length of the array. The opposite operation is push
Array#shift
is similar to pop
, except it removes the first element. The opposite operation is unshift
.
Upvotes: 302
Reputation: 2500
We can remove using
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*",
"regex1": "^http://.*",
"regex2": "^http://.*",
"regex3": "^http://.*",
"regex4": "^http://.*"
};
delete myObject.regex; // using delete object.property
// Or
delete myObject['regex1']; // using delete object['property']
const { regex2, regex3, regex4, ...newMyObject } = myObject;
console.log(newMyObject);
Upvotes: 2
Reputation: 2241
I have used Lodash "unset" to make it happen for a nested object also... only this needs to write small logic to get the path of the property key which is expected by the omit method.
var a = {"bool":{"must":[{"range":{"price_index.final_price":{"gt":"450", "lt":"500"}}}, {"bool":{"should":[{"term":{"color_value.keyword":"Black"}}]}}]}};
function getPathOfKey(object,key,currentPath, t){
var currentPath = currentPath || [];
for(var i in object){
if(i == key){
t = currentPath;
}
else if(typeof object[i] == "object"){
currentPath.push(i)
return getPathOfKey(object[i], key,currentPath)
}
}
t.push(key);
return t;
}
document.getElementById("output").innerHTML =JSON.stringify(getPathOfKey(a,"price_index.final_price"))
<div id="output">
</div>
var unset = require('lodash.unset');
unset(a, getPathOfKey(a, "price_index.final_price"));
Upvotes: 10
Reputation: 522
import omit from 'lodash/omit';
const prevObject = {test: false, test2: true};
// Removes test2 key from previous object
const nextObject = omit(prevObject, 'test2');
R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
Upvotes: 16
Reputation: 3258
You can use a filter like below
var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
// Way 1
let filter1 = {}
Object.keys({...myObject}).filter(d => {
if(d !== 'regex'){
filter1[d] = myObject[d];
}
})
console.log(filter1)
// Way 2
let filter2 = Object.fromEntries(Object.entries({...myObject}).filter(d =>
d[0] !== 'regex'
))
console.log(filter2)
Upvotes: 11
Reputation: 1271
Two ways to delete an object
using for ... in
function deleteUser(key) {
const newUsers = {};
for (const uid in users) {
if (uid !== key) {
newUsers[uid] = users[uid];
}
return newUsers
}
or
delete users[key]
Upvotes: 2
Reputation: 1172
Here's an ES6 way to remove the entry easily:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
const removeItem = 'regex';
const { [removeItem]: remove, ...rest } = myObject;
console.log(remove); // "^http://.*"
console.log(rest); // Object { ircEvent: "PRIVMSG", method: "newURI" }
Upvotes: 12
Reputation: 8740
@johnstock, we can also use JavaScript's prototyping concept to add method to objects to delete any passed key available in calling object.
Above answers are appreciated.
var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
// 1st and direct way
delete myObject.regex; // delete myObject["regex"]
console.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' }
// 2 way - by using the concept of JavaScript's prototyping concept
Object.prototype.removeFromObjectByKey = function(key) {
// If key exists, remove it and return true
if (this[key] !== undefined) {
delete this[key]
return true;
}
// Else return false
return false;
}
var isRemoved = myObject.removeFromObjectByKey('method')
console.log(myObject) // { ircEvent: 'PRIVMSG' }
// More examples
var obj = {
a: 45,
b: 56,
c: 67
}
console.log(obj) // { a: 45, b: 56, c: 67 }
// Remove key 'a' from obj
isRemoved = obj.removeFromObjectByKey('a')
console.log(isRemoved); //true
console.log(obj); // { b: 56, c: 67 }
// Remove key 'd' from obj which doesn't exist
var isRemoved = obj.removeFromObjectByKey('d')
console.log(isRemoved); // false
console.log(obj); // { b: 56, c: 67 }
Upvotes: 11
Reputation: 8766
This post is very old and I find it very helpful so I decided to share the unset function I wrote in case someone else see this post and think why it's not so simple as it in PHP unset function.
The reason for writing this new unset
function, is to keep the index of all other variables in this hash_map. Look at the following example, and see how the index of "test2" did not change after removing a value from the hash_map.
function unset(unsetKey, unsetArr, resort) {
var tempArr = unsetArr;
var unsetArr = {};
delete tempArr[unsetKey];
if (resort) {
j = -1;
}
for (i in tempArr) {
if (typeof(tempArr[i]) !== 'undefined') {
if (resort) {
j++;
} else {
j = i;
}
unsetArr[j] = tempArr[i];
}
}
return unsetArr;
}
var unsetArr = ['test', 'deletedString', 'test2'];
console.log(unset('1', unsetArr, true)); // output Object {0: "test", 1: "test2"}
console.log(unset('1', unsetArr, false)); // output Object {0: "test", 2: "test2"}
Upvotes: 26
Reputation: 9779
If you don't want to modify the original object.
Remove a property without mutating the object
If mutability is a concern, you can create a completely new object by copying all the properties from the old, except the one you want to remove.
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
let prop = 'regex';
const updatedObject = Object.keys(myObject).reduce((object, key) => {
if (key !== prop) {
object[key] = myObject[key]
}
return object
}, {})
console.log(updatedObject);
Upvotes: 5
Reputation: 1
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
obj = Object.fromEntries(
Object.entries(myObject).filter(function (m){
return m[0] != "regex"/*or whatever key to delete*/
}
))
console.log(obj)
You can also just treat the object like a2d
array using Object.entries
, and use splice to remove an element as you would in a normal array, or simply filter through the object, as one would an array, and assign the reconstructed object back to the original variable
Upvotes: 5
Reputation: 57941
Objects in JavaScript can be thought of as maps between keys and values. The delete
operator is used to remove these keys, more commonly known as object properties, one at a time.
var obj = {
myProperty: 1
}
console.log(obj.hasOwnProperty('myProperty')) // true
delete obj.myProperty
console.log(obj.hasOwnProperty('myProperty')) // false
The delete
operator does not directly free memory, and it differs from simply assigning the value of null
or undefined
to a property, in that the property itself is removed from the object. Note that if the value of a deleted property was a reference type (an object), and another part of your program still holds a reference to that object, then that object will, of course, not be garbage collected until all references to it have disappeared.
delete
will only work on properties whose descriptor marks them as configurable.
Upvotes: 1130
Reputation: 6364
I personally use Underscore.js or Lodash for object and array manipulation:
myObject = _.omit(myObject, 'regex');
Upvotes: 43
Reputation: 4192
Another alternative is to use the Underscore.js library.
Note that _.pick()
and _.omit()
both return a copy of the object and don't directly modify the original object. Assigning the result to the original object should do the trick (not shown).
Reference: link _.pick(object, *keys)
Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys).
var myJSONObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
_.pick(myJSONObject, "ircEvent", "method");
=> {"ircEvent": "PRIVMSG", "method": "newURI"};
Reference: link _.omit(object, *keys)
Return a copy of the object, filtered to omit the blacklisted keys (or array of keys).
var myJSONObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
_.omit(myJSONObject, "regex");
=> {"ircEvent": "PRIVMSG", "method": "newURI"};
For arrays, _.filter()
and _.reject()
can be used in a similar manner.
Upvotes: 128