To remove all toDelete_...
properties, you can utilize the array.prototype.forEach
method to loop through the array
and check for any matching toDelete
properties within each object.
If a match is found, the property is then deleted.
var data = [
{
"toDelete_item1": [],
"name": "Joe"
},
{
"toDelete_item2": [],
"name": "Adam"
},
{
"name": "Peter",
"toDelete_item3": []
}
];
data.forEach(function(item,index){
for(var prop in item) {
if (prop.match(/toDelete/) !== null) {
delete item[prop];
}
}
});
console.log(data);
This solution works specifically for the given scenario. To make it more versatile, let's convert it into a function that only deletes properties within objects contained in the data array, without recursion.
In this revised version, we use the match
method instead of indexOf
for increased flexibility. No need to check if the property exists; either there is a match or not.
var data = [
{"toDelete_item1": [], "name": "Joe"},
{"toDelete_item2": [], "name": "Adam"},
{"name": "Peter", "toDelete_item3": []},
["toDelete_item4", "Foo"],
"toDelete_item5"
];
function delPropFromObjsInArr (reg, arr) {
var regex = new RegExp(reg);
arr.forEach(function(item, index){
if (item === Object(item)) {
for(var p in item) {
if (p.match(regex) !== null) {
delete item[p];
}
}
}
});
}
delPropFromObjsInArr("toDelete", data);
console.log(data);