How to omit specific properties from an object in JavaScript

后端 未结 14 1263
无人共我
无人共我 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: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));

提交回复
热议问题