'How to remove all properties that match a regex from a JavaScript object?

I have the following JS object:

let obj = {
    'a': 1,
    'a-gaboom': 1,
    'b': 1,
    'b-gaboom': 1
};

I want to delete all fields that end with '-gaboom'.

I could do it manually with:

delete obj['a-gaboom'];
delete obj['b-gaboom'];

But I'd like to do it dynamically using a RegExp?



Solution 1:[1]

You can get the entries (array of [key, value] pairs) of the object with Object.entries(). Filter the array of entries, and keep only entries with a key that doesn't end with -gaboom. Convert back to an object via Object.fromEntries():

const obj = {'a': 1,'a-gaboom': 1,'b': 1,'b-gaboom': 1}

const result = Object.fromEntries(
  Object.entries(obj)
    .filter(([key]) => !key.endsWith('-gaboom'))
)

console.log(result)

Solution 2:[2]

taking a cue from the other answers, with this generic function it is possible to eliminate all the keys that verify a specific condition while mutating the original object.

deleteKeys = function (obj, fn) {
  Object.entries(obj)
    .filter(([key, value]) => fn(key, value))
    .forEach(([key]) => delete obj[key]);
};

const obj = {'a': 1,'a-gaboom': 1,'b': 1,'b-gaboom': 1};

deleteKeys(obj, (key) => !key.endsWith("-gaboom"));

console.log(obj)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ori Drori
Solution 2 Mario