user6898463
user6898463

Reputation:

"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?

Upvotes: 4

Views: 2143

Answers (3)

Rajneesh
Rajneesh

Reputation: 5308

Above answers are great, I'm sharing my try:

var myObject = { a: 1, b: 2, c: 3, d: 4};
let remove=(obj, arr)=> {
  let output=[];
  for(const [key, value] of Object.entries(obj)){
  if(!arr.includes(key)){
     output.push([key,value]);
    }
  }
 return Object.fromEntries(output);
}
console.log(remove(myObject, ['a']));
console.log(remove(myObject, ['a', 'c']));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

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

Upvotes: 3

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

You can do it using reduce and Object.entries(). You can try this:

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

const removeProps = (object, keys) => {
    return Object.entries(object).reduce((a, [key, value]) => (keys.indexOf(key) === -1 ? {...a, [key]: value}: a), {});
}

console.log(removeProps(myObject, ['b']));
console.log(removeProps(myObject, ['b', 'c']));
console.log('Original Object: ', myObject);
.as-console-wrapper{min-height: 100%!important; top: 0}

Upvotes: 2

Related Questions