Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove property for all objects in array

People also ask

How do I remove all properties of an object?

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!

How do you remove a property from an array of objects in typescript?

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:

  • if you want to be compatible with IE8, you'd need a shim for forEach. As you mention prototype, prototype.js also has a shim.
  • 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']);
});