[javascript] Remove property for all objects in array

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?

This question is related to javascript javascript-objects

The answer is


For my opinion this is the simplest variant

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

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

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

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


To remove some key value pair form object array uses Postgres SQL as database like this example:

This is user function return user details object, we have to remove "api_secret" key from rows :

    function getCurrentUser(req, res, next) { // user function
    var userId = res.locals.userId;
    console.log(userId)
    db.runSQLWithParams("select * from users where id = $1", [userId], function(err, rows) {
      if(err){
        console.log(err)
      }
      var responseObject = {
        _embedded: rows,
      }
      responseObject._embedded[0].api_secret = undefined
      // console.log(api);
      // console.log(responseObject);
      res.json(responseObject);
    }); 
}

The above function return below object as JSON response before

 {
    "_embedded": [
        {
            "id": "0123abd-345gfhgjf-dajd4456kkdj",
            "secret_key: "secret",
            "email": "[email protected]",
            "created": "2020-08-18T00:13:16.077Z"
        }
    ]
}

After adding this line responseObject._embedded[0].api_secret = undefined It gives below result as JSON response:

{
        "_embedded": [
            {
                "id": "0123abd-345gfhgjf-dajd4456kkdj",
                "email": "[email protected]",
                "created": "2020-08-18T00:13:16.077Z"
            }
        ]
    }

ES6:

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

If you use underscore.js:

var strippedRows = _.map(rows, function (row) {
    return _.omit(row, ['bad', 'anotherbad']);
});

_x000D_
_x000D_
var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];_x000D_
var results = array.map(function(item){_x000D_
  return {good : item["good"]}_x000D_
});_x000D_
console.log(JSON.stringify(results));
_x000D_
_x000D_
_x000D_


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

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

Disclaimer: I'm the author of object-fields


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

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

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

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)


The shortest way in ES6:

array.forEach(e => {delete e.someKey});

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;

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