Delete multiple keys in object javascript

If you want a solution that feels built-in, you could add a utility function that works like Object.defineProperties(), so you can add properties to a given object, but now also delete properties by handing in a null property descriptor.

Object.defineProperties() throws an error if a property descriptor is not an object, so we can safely use a "falsy" value to indicate that the property is to be deleted.

Here is the code:

function unDefineProperties(obj, propertyDescriptors) {
  const [normalDescriptors, toBeDeletedDescriptors] =
    partition(Object.entries(propertyDescriptors),([_, descriptor]) => descriptor);
  Object.defineProperties(obj, Object.fromEntries(normalDescriptors));
  toBeDeletedDescriptors.forEach(([name, _]) => delete obj[name]);
  return obj;
}

The name of the function is supposed to be read as "(un)define properties", i.e. "define or delete properties".

It splits the given propertyDescriptors into the "normal" ones with a non-"falsy" value and the "to-be-deleted" ones with a "falsy" value, using the utility function partition (defined in the code snippet below, borrowed from this answer).

It then calls Object.defineProperties() with a property descriptors object reconstructed from the "normal" entries.

After that (because the first step may fail due to incorrect property descriptors), all "to-be-deleted" entries delete the corresponding properties in obj.

Finally, obj is returned, to mimic the convenient behavior of Object.defineProperties().

The resulting function is compatible with the original Object.defineProperties() (of course apart from the behavior for "falsy" property descriptors) and thus could be used as a replacement for that original function. If you want to do so, for consistency, you should also replace Object.defineProperty() (singular!) by a similar function that handles a "falsy" property descriptor by deleting the corresponding property (left as an exercise for the reader ;-)).

Here is the complete code with a usage example:

function partition(array, filter) {
  let pass = [], fail = [];
  array.forEach((e, idx, arr) => (filter(e, idx, arr) ? pass : fail).push(e));
  return [pass, fail];
}

function unDefineProperties(obj, propertyDescriptors) {
  const [normalDescriptors, toBeDeletedDescriptors] =
    partition(Object.entries(propertyDescriptors),([_, descriptor]) => descriptor);
  Object.defineProperties(obj, Object.fromEntries(normalDescriptors));
  toBeDeletedDescriptors.forEach(([name, _]) => delete obj[name]);
  return obj;
}

// Usage example:

const obj = { a: 'A', b: 'B', c: 'C'};

unDefineProperties(obj, {
  a: null,
  c: null,
  d: { value: "D", enumerable: true }
});

console.log(obj); // logs { "b": "B", "d": "D" }

Delete Multiple Keys From Object Javascript With Code Examples

Good day, folks. In this post, we’ll examine how to find a solution to the programming challenge titled Delete Multiple Keys From Object Javascript.

var obj = {a: 1, b: 2, c: 3, d: 4, e: 5 };

['c', 'e'].forEach(e => delete obj[e]);

// obj is now {a:1, b:2, d:4}

Another method that is described below with code examples can be used to tackle the same issue Delete Multiple Keys From Object Javascript.

const obj = {
        a: 'dog',
        b: 'cat',
        c: 'mouse',
        d: 'cow',
        e: 'horse',
    };
const {a, e, ...updatedObject} = obj;

// output
console.log(updatedObject)

We were able to figure out how to solve the Delete Multiple Keys From Object Javascript code by looking at a range of other samples.

In JavaScript, I can delete an object's key with,There is no built in js function to delete multiple keys yet, you can use any library for this such as underscore.js to do this. , About ,Is there an efficient way to delete multiple keys using one line? Something that looks like:

Here's a one-liner similar to what you're requesting.

var obj = {
   a: 1,
   b: 2,
   c: 3,
   d: 4,
   e: 5
};

['c', 'e'].forEach(e => delete obj[e]);

const obj = {
   a: 'dog',
   b: 'cat',
   c: 'mouse',
   d: 'cow',
   e: 'horse',
};
const {
   a,
   e,
   ...updatedObject
} = obj;


console.log(updatedObject)

There is no built in js function to delete multiple keys yet, you can use any library for this such as underscore.js to do this.

_.omit({
   name: 'moe',
   age: 50,
   userid: 'moe1'
}, 'userid'); => {
   name: 'moe',
   age: 50
}



_.omit({
   name: 'moe',
   age: 50,
   userid: 'moe1'
}, function(value, key, object) {
   return _.isNumber(value);
}); => {
   name: 'moe',
   userid: 'moe1'
}

Example:

var obj = {
   x: 1,
   y: 2,
   z: 3
};
var result = _.omit(obj, ['x', 'y']);
console.log(result);


result = {
   z: 3
};

There is no built-in function, but one way you could do it is to add the multidelete method to the Object prototype. It's perhaps a little bit overkill, but you might find it useful.

if (!('multidelete' in Object.prototype)) {
   Object.defineProperty(Object.prototype, 'multidelete', {
      value: function() {
         for (var i = 0; i < arguments.length; i++) {
            delete this[arguments[i]];
         }
      }
   });
}

var obj = {
   a: 1,
   b: 2,
   c: 3,
   d: 4,
   e: 5
};

obj.multidelete('c', 'e'); 


Suggestion : 2

You can remove a property from an object using destructuring in combination with the ... rest operator. Destructuring splits an object into its individual keys and you can remove those that you don’t want in the new one.,Here’s an example removing the group property from a user object:,You probably know the globally available delete operator to remove a property from a JavaScript object. But be careful: deleting a property using delete mutates the original object!,The code snippet destructures the user into a group property and everything else called userWithoutGroup.

Here’s an example removing the group property from a user object:

const user = {
   id: 1,
   name: 'Marcus',
   group: 'admin'
}

const {
   ['group']: group, ...userWithoutGroup
} = user
console.log(userWithoutGroup)

You can also put this functionality into a reusable utility function:

function withoutProperty(obj, property) {
   const {
      [property]: unused, ...rest
   } = obj

   return rest
}

Then use the withoutProperty utility function like this:

const user = {
   id: 1,
   name: 'Marcus',
   group: 'admin'
}

const userWithoutGroup = withoutProperty(user, 'group')


Suggestion : 3

The delete operator is used to remove the key from an object, and its key and value are removed from an object.,removed the company key and its values from an object using the delete operator,Assign undefined value to key, and key and value are removed from an object.,omit method in lodash removes object own properties, Omit method accepts objects and keys or a list of keys to be removed. Here is an example

let obj = {
   "model": "alto",
   "company": "Maruthi",
   "type": "car"
}

delete object[key];
or
delete object.key

console.log(obj);
delete obj.company
for (const property in obj) {
   console.log(`${property}: ${obj[property]}`);
}
console.log(obj.company);

{
   model: 'alto',
   company: 'Maruthi',
   type: 'car'
}
model: alto
type: car
undefined


Suggestion : 4

var obj = {
   a: 1,
   b: 2,
   c: 3,
   d: 4,
   e: 5
};

['c', 'e'].forEach(e => delete obj[e]);

const obj = {
   a: 'dog',
   b: 'cat',
   c: 'mouse',
   d: 'cow',
   e: 'horse',
};
const {
   a,
   e,
   ...updatedObject
} = obj;


console.log(updatedObject)


Suggestion : 5

There is no built in js function to delete multiple keys yet, you can use any library for this such as underscore.js to do this. ,delete myObject[myKey];,Is there an efficient way to delete multiple keys using one line? Something that looks like:,multiDelete myObject[keyOne, keyTwo, keyThree];

Here's a one-liner similar to what you're requesting.

var obj = {
   a: 1,
   b: 2,
   c: 3,
   d: 4,
   e: 5
};
['c', 'e'].forEach(e => delete obj[e]);

2._

const obj = {
   a: 'dog',
   b: 'cat',
   c: 'mouse',
   d: 'cow',
   e: 'horse',
};
const {
   a,
   e,
   ...updatedObject
} = obj;

console.log(updatedObject)

There is no built in js function to delete multiple keys yet, you can use any library for this such as underscore.js to do this.

_.omit({
   name: 'moe',
   age: 50,
   userid: 'moe1'
}, 'userid'); => {
   name: 'moe',
   age: 50
}

_.omit({
   name: 'moe',
   age: 50,
   userid: 'moe1'
}, function(value, key, object) {
   return _.isNumber(value);
}); => {
   name: 'moe',
   userid: 'moe1'
}


Suggestion : 6

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically. , The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. , In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain: , If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).

delete object.property
delete object['property']

const Employee = {
   age: 28,
   name: 'abc',
   designation: 'developer'
}

console.log(delete Employee.name); 
console.log(delete Employee.age); 



console.log(delete Employee.salary); 

const Employee = {};
Object.defineProperty(Employee, 'name', {
   configurable: false
});

console.log(delete Employee.name); 

var nameOther = 'XYZ';


Object.getOwnPropertyDescriptor(window, 'nameOther');









delete nameOther; 


Suggestion : 7

When multiple keys are to be removed then the keys can be stored in an array and can be passed to a function that uses a loop to delete the required keys in the array. ,Using delete operator. When only a single key is to be removed we can directly use the delete operator specifying the key in an object. ,In JavaScript objects store data in the form of key-value pairs where the key may be any property of the object. In this article let us see how to remove key-value pairs corresponding to a given key in the object.,Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

delete(object_name.key_name);

delete(object_name[key_name]);

Output:

"After removal: " [object Object] {
   Age: 30,
   Name: "Raghav",
   Organisation: "GeeksforGeeks",
   Sex: "Male",
   Work: "Web Developer",
   YearsOfExperience: 6
}


How to delete multiple keys from object in JavaScript?

There is one simple fix using the library lodash. The _. omit function takes your object and an array of keys that you want to remove and returns a new object with all the properties of the original object except those mentioned in the array.

How do I remove multiple properties from an object?

You can simply use the delete operator to remove property from an object. If you want to delete multiple properties, you have to use the delete operator multiple times in the same function.

How do you delete object keys?

The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.

How do I remove a specific key from an array of objects?

To remove a property from all objects in an array: Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.