Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

With ES6, you may deconstruct each object to create new one without named attributes:

const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)

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']);
});

You can follow this, more readable, not expectation raise due to key not found :

data.map((datum) => {
  return {
    'id':datum.id,
    'title':datum.login
  }
});

For my opinion this is the simplest variant

array.map(({good}) => ({good}))

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;

var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];

const cleanArray = array.map(item=>{
  delete item.bad
  return item
})
console.log(cleanArray)

The shortest way in ES6:

array.forEach(e => {delete e.someKey});
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'}]

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)

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);

ES6:

const newArray = array.map(({keepAttr1, keepAttr2}) => ({keepAttr1, newPropName: keepAttr2}))

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
})
}

By reduce:

const newArray = oldArray.reduce((acc, curr) => {
  const { remove_one, remove_two, ...keep_data } = curr;
  acc.push(keep_data);
  return acc;
}, []);

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);

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' } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-fields@2.0.19"></script>

Disclaimer: I'm the author of object-fields

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));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top