Here is what you can do to delete all toDelele_...
properties. Using the array.prototype.forEach
to iterate over the array
, then look for a match of toDelete
as a property within every obj.
If there is a match, delete the property.
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);
As mentioned in the comments that this solution will only work for the given scenario, lets turn this into a more usable function. Which will only delete properties within an object which is an item of the data array. Not recursively though.
I don't see the need of checking if the property exists, either there is a match or not (pleas correct me if i am wrong). Sticking with match
other than indexOf
seems to be just a bit more flexible.
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);