Remove property for all objects in array
JavascriptJavascript ObjectsJavascript Problem Overview
I want to remove the bad
property from every object in the array. Is there a better way to do it than using a for
loop and deleting it from every object?
var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"},...];
for (var i = 0, len = array.length; i < len; i++) {
delete array[i].bad;
}
Just seems like there should be a way to use prototype
, or something. I don’t know. Ideas?
Javascript Solutions
Solution 1 - Javascript
With ES6, you may deconstruct each object to create new one without named attributes:
const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)
Solution 2 - Javascript
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 toundefined
or just build new objects without the property.
Solution 3 - Javascript
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;
});
Solution 4 - Javascript
If you use underscore.js:
var strippedRows = _.map(rows, function (row) {
return _.omit(row, ['bad', 'anotherbad']);
});
Solution 5 - Javascript
You can follow this, more readable, not expectation raise due to key not found :
data.map((datum) => {
return {
'id':datum.id,
'title':datum.login
}
});
Solution 6 - Javascript
For my opinion this is the simplest variant
array.map(({good}) => ({good}))
Solution 7 - Javascript
A solution using prototypes is only possible when your objects are alike:
function Cons(g) { this.good = g; }
Cons.prototype.bad = "something common";
var array = [new Cons("something 1"), new Cons("something 2"), …];
But then it's simple (and O(1)
):
delete Cons.prototype.bad;
Solution 8 - Javascript
var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];
const cleanArray = array.map(item=>{
delete item.bad
return item
})
console.log(cleanArray)
Solution 9 - Javascript
The shortest way in ES6:
array.forEach(e => {delete e.someKey});
Solution 10 - Javascript
This question is a bit old now, but I would like to offer an alternative solution that doesn't mutate source data and requires minimal manual effort:
function mapOut(sourceObject, removeKeys = []) {
const sourceKeys = Object.keys(sourceObject);
const returnKeys = sourceKeys.filter(k => !removeKeys.includes(k));
let returnObject = {};
returnKeys.forEach(k => {
returnObject[k] = sourceObject[k];
});
return returnObject;
}
const array = [
{"bad": "something", "good":"something"},
{"bad":"something", "good":"something"},
];
const newArray = array.map(obj => mapOut(obj, [ "bad", ]));
It's still a little less than perfect, but maintains some level of immutability and has the flexibility to name multiple properties that you want to remove. (Suggestions welcome)
Solution 11 - Javascript
const arr = [
{id: 1, name: 'user1', test: 'abc'},
{id: 2, name: 'user2', test: 'xyz'},
];
const newArr = arr.map(({test, ...rest}) => {
return rest;
});
console.log(newArr);
// 👇️ [{id: 1, name: 'User1'}, {id: 2, name: 'User2'}]
The function we pass to the Array.map method gets invoked with each element in the array.
We destructure the test property from each object and use the rest operator (...) to get the rest of the object's properties.
We return the rest of the object's properties from the function, practically excluding the test property.
const arr = [
{id: 1, name: 'Tom', test: 'abc'},
{id: 2, name: 'Bob', test: 'xyz'},
];
arr.forEach(object => {
delete object['test'];
});
console.log(arr);
// 👇️ [{id: 1, name: 'Tom'}, {id: 2, name: 'Bob'}]
Solution 12 - Javascript
I will suggest to use Object.assign
within a forEach()
loop so that the objects are copied and does not affect the original array of objects
var res = [];
array.forEach(function(item) {
var tempItem = Object.assign({}, item);
delete tempItem.bad;
res.push(tempItem);
});
console.log(res);
Solution 13 - Javascript
ES6:
const newArray = array.map(({keepAttr1, keepAttr2}) => ({keepAttr1, newPropName: keepAttr2}))
Solution 14 - Javascript
This works well for me!
export function removePropertiesFromArrayOfObjects(arr = [], properties = []) {
return arr.map(i => {
const newItem = {}
Object.keys(i).map(key => {
if (properties.includes(key)) { newItem[key] = i[key] }
})
return newItem
})
}
Solution 15 - Javascript
By reduce:
const newArray = oldArray.reduce((acc, curr) => {
const { remove_one, remove_two, ...keep_data } = curr;
acc.push(keep_data);
return acc;
}, []);
Solution 16 - Javascript
i have tried with craeting a new object without deleting the coulmns in Vue.js.
> let data =this.selectedContactsDto[];
//selectedContactsDto[] = object with list of array objects created in my project
> console.log(data); > let newDataObj= data.map(({groupsList,customFields,firstname, ...item }) => item); > console.log("newDataObj",newDataObj);
Solution 17 - Javascript
There are plenty of libraries out there. It all depends on how complicated your data structure is (e.g. consider deeply nested keys)
We like object-fields as it also works with deeply nested hierarchies (build for api fields parameter). Here is a simple code example
// const objectFields = require('object-fields');
const array = [ { bad: 'something', good: 'something' }, { bad: 'something', good: 'something' } ];
const retain = objectFields.Retainer(['good']);
retain(array);
console.log(array);
// => [ { good: 'something' }, { good: 'something' } ]
<script src="https://bundle.run/[email protected]"></script>
.as-console-wrapper {max-height: 100% !important; top: 0}
Disclaimer: I'm the author of object-fields
Solution 18 - Javascript
var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];
var results = array.map(function(item){
return {good : item["good"]}
});
console.log(JSON.stringify(results));