Sometimes, we want to remove certain properties from object in JavaScript.
In this article, we’ll look at how to remove certain properties from object in JavaScript.
How to remove certain properties from object in JavaScript?
To remove certain elements from map in JavaScript, we can use some object methods and the array filter
method.
For instance, we write:
const obj = {}
obj.XKey1 = "Value1";
obj.XKey2 = "Value2";
obj.YKey3 = "Value3";
obj.YKey4 = "Value4";
const entries = Object.entries(obj).filter(([key]) => key.includes('XKey'))
const newObj = Object.fromEntries(entries)
console.log(newObj)
to call Objec.entries
to return an array of key-value pair arrays.
Then we call filter
to check if the key
string has 'XKey'
in it.
Next, we call Object.fromEntries
with entries
to create an object from the key-value pair array returned by filter
.
Therefore, newObj
is
{
XKey1: "Value1",
XKey2: "Value2"
}
Conclusion
To remove certain elements from map in JavaScript, we can use some object methods and the array filter
method.