I need to find the fastest way to remove all $meta
properties and their values from an object, for example:
{
"part_one": {
"name": "My Name",
"something": "123",
"$meta": {
"test": "test123"
}
},
"part_two": [
{
"name": "name",
"dob": "dob",
"$meta": {
"something": "else",
"and": "more"
}
},
{
"name": "name",
"dob": "dob"
}
],
"$meta": {
"one": 1,
"two": 2
}
}
Should become the following given that the $meta
property could be at any point in the object so some form of recursion will probably be needed.
{
"part_one": {
"name": "My Name",
"something": "123"
},
"part_two": [
{
"name": "name",
"dob": "dob"
},
{
"name": "name",
"dob": "dob"
}
]
}
Any help or advice would be greatly appreciated!
Thank you!
Remove a Property from a JS Object with the Delete Operator delete object. property; delete object['property'];
Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.
The semantically correct way to remove a property from an object is to use the delete keyword.
Use delete to Remove Object Keys The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.
A simple self-calling function can do it.
function removeMeta(obj) {
for(prop in obj) {
if (prop === '$meta')
delete obj[prop];
else if (typeof obj[prop] === 'object')
removeMeta(obj[prop]);
}
}
var myObj = {
"part_one": {
"name": "My Name",
"something": "123",
"$meta": {
"test": "test123"
}
},
"part_two": [
{
"name": "name",
"dob": "dob",
"$meta": {
"something": "else",
"and": "more"
}
},
{
"name": "name",
"dob": "dob"
}
],
"$meta": {
"one": 1,
"two": 2
}
}
function removeMeta(obj) {
for(prop in obj) {
if (prop === '$meta')
delete obj[prop];
else if (typeof obj[prop] === 'object')
removeMeta(obj[prop]);
}
}
removeMeta(myObj);
console.log(myObj);
As @floor commented above:
JSON.parse(JSON.stringify(obj, (k,v) => (k === '$meta')? undefined : v))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With