How to omit specific properties from an object in JavaScript

后端 未结 14 1254
无人共我
无人共我 2021-02-01 14:50

Is there a clean way to return a new object that omits certain properties that the original object contains without having to use something like lodash?

相关标签:
14条回答
  • 2021-02-01 15:31

    If you already use lodash, you may also do omit(obj, ["properties", "to", "omit"]) to get a new Object without the properties provided in the array.

    0 讨论(0)
  • 2021-02-01 15:34

    Omit and array of keys, using ES7 w/ recursion.

    function omit(keys, obj) {
      if (!keys.length) return obj
      const { [keys.pop()]: omitted, ...rest } = obj;
      return omit(keys, rest);
    }
    

    This builds on top of @Eddie Cooro answer.

    0 讨论(0)
  • 2021-02-01 15:35

    One solution, I'm sure many others exist.

    const testObj = {
        prop1: 'value1',
        prop2: 'value2',
        prop3: 'value3'
    };
    
    const removeProps = (...propsToFilter) => obj => {
       return Object.keys(obj)
       .filter(key => !propsToFilter.includes(key))
       .reduce((newObj, key) => {
           newObj[key] = obj[key];
           return newObj;
       }, {});
    };
    
    
    console.log(removeProps('prop3')(testObj));
    console.log(removeProps('prop1', 'prop2')(testObj));

    Edit: I always forget about delete...

    const testObj = {
        prop1: 'value1',
        prop2: 'value2',
        prop3: 'value3'
    };
    
    const removeProps = (...propsToFilter) => obj => {
       const newObj = Object.assign({}, obj);
       propsToFilter.forEach(key => delete newObj[key]);
       return newObj;
    };
    
    
    console.log(removeProps('prop3')(testObj));
    console.log(removeProps('prop1', 'prop2')(testObj));

    0 讨论(0)
  • 2021-02-01 15:40

    If you know the list of the properties that you want preserved as well as omitted, the following "whitelisting" approach should work:

    const exampleFilter = ({ keepMe, keepMeToo }) => ({ keepMe, keepMeToo })
    
    console.log(
      exampleFilter({
        keepMe: 'keepMe',
        keepMeToo: 'keepMeToo',
        omitMe: 'omitMe',
        omitMeToo: 'omitMeToo'
      })
    )

    0 讨论(0)
  • 2021-02-01 15:40

    Sure, why not something like:

    var original = {
      name: 'Rory',
      state: 'Bored',
      age: '27'
    };
    
    var copied = Object.assign({}, original);
    delete copied.age;
    
    console.log(copied);
    

    https://jsfiddle.net/4nL08zk4/

    0 讨论(0)
  • There's the blacklist package on npm which has a very flexible api.

    Also a situational trick using the object rest-spread proposal (stage-3).

    const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4};
    a // 1
    b // 2
    rest // {c: 3, d: 4}
    

    This is often used in react components where you want to use a few properties and pass the rest as props to a <div {...props} /> or similar.

    0 讨论(0)
提交回复
热议问题