Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!
You'd use filter to remove or keep items in an array, not properties. delete , here, creates side-effects. This answer is using filter in a completely unsemantic way as a general-purpose iteration method.
With ES6, you may deconstruct each object to create new one without named attributes:
const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)
The only other ways are cosmetic and are in fact loops.
For example :
array.forEach(function(v){ delete v.bad });
Notes:
delete
is one of the worst "optimization killers". Using it often breaks the performances of your applications. You can't avoid it if you want to really remove a property but you often can either set the property to undefined
or just build new objects without the property.I prefer to use map to delete the property and then return the new array item.
array.map(function(item) {
delete item.bad;
return item;
});
If you use underscore.js:
var strippedRows = _.map(rows, function (row) {
return _.omit(row, ['bad', 'anotherbad']);
});
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