Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Removing" multiple properties from an object without mutation

I'm searching a for a way to create a function. in which I can pass an object and an array of properties (keys) I want gone. That function will return me a new object that doesn't have the keys I've specified.

function(keys: array, obj: object) {...}

Question is - how do I do that with multiple properties?

I've searched and only found this kind of solution:

const myObject = {
  a: 1,
  b: 2,
  c: 3
};

const { a, ...noA } = myObject;

But it only works if I want to remove only ONE key. What if I want to remove multiple, using an array I just passed? How do I do that without mutating the original array or manually creating copies of it?


1 Answers

You could destructure the object by taking a computed property for unwanted properties.

const
    without = (object, keys) => keys.reduce((o, k) => {
        const { [k]: _ , ...p } = o;
        return p;
    }, object),
    myObject = { a: 1, b: 2, c: 3 },
    keys = ['a', 'b'],
    result = without(myObject, keys);

console.log(result);
like image 182
Nina Scholz Avatar answered Sep 03 '25 18:09

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!