Cloning javascript object omitting one property

时间:2019-03-19 14:56:18

标签: javascript

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 个答案:

答案 0 :(得分: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())

答案 1 :(得分: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' }