3

What's the best way in JavaScript for returning an object omitting just one or more properties?

I can assign a key to undefined and that works for sure, but what if want to completely get rid of that key?

function removeCKey() {
  const obj = {a: 'a', b: 'b', c: 'c'}
  return {
    ...obj,
    c: undefined,
  };
}

const myObj = removeCKey();

Also, I want to avoid creating an intermediate object where I use the spread operator like this

function removeCKey() {
  const obj = {a: 'a', b: 'b', c: 'c'}
  const {c, ...rest} = newObj

  return rest;
}

const myObj = removeCKey();

2 Answers2

2

You can use ES6 object destructuring assignment.

function removeKeys() {
  const obj = {
    a: 'a',
    b: 'b',
    c: 'c'
  };

  // extract property c in variable c
  // and rest of the value into res 
  let { c, ...res } = obj;

  return res;
}

console.log(removeKeys())
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

Just delete what you don't need:

function omit(obj, keys) {
  const newObj = { ...obj };  // shallow copy...
  keys.forEach(key => {
    delete newObj[key];  // ... and `delete`.
  });
  return newObj;
}

omit({a: 'a', b: 'b', c: 'c'}, ['c']);

outputs

{ a: 'a', b: 'b' }
AKX
  • 152,115
  • 15
  • 115
  • 172