How to omit specific properties from an object in JavaScript

后端 未结 14 1252
无人共我
无人共我 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:20

    In modern environments you can use this code snippet:

    function omit(key, obj) {
      const { [key]: omitted, ...rest } = obj;
      return rest;
    }
    
    0 讨论(0)
  • 2021-02-01 15:24

    const x = {obj1: 1, obj2: 3, obj3:26};
    
    
    const {obj1,obj2, ...rest} = x;
    console.log(rest)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>

    0 讨论(0)
  • 2021-02-01 15:26
    const {omittedPropertyA, omittedPropertyB, ...remainingObject} = originalObject;
    

    Explanation:

    With ES7

    you could use object destructuring and the spread operator to omit properties from a javascript object:

    const animalObject = { 'bear': 1, 'snake': '2', 'cow': 3 };
     
    const {bear, ...other} = animalObject
    
    // other is: { 'snake': '2', 'cow:'  3}
    

    source: https://remotedevdaily.com/two-ways-to-omit-properties-from-a-javascript-object/

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

    You can use Object.assign(), delete

    var not = ["a", "b"]; // properties to delete from obj object
    var o = Object.assign({}, obj);
    for (let n of not) delete o[n];
    

    Alternatively

    var props = ["c", "d"];
    let o = Object.assign({}, ...props.map(prop => ({[prop]:obj[prop]})));
    
    0 讨论(0)
  • 2021-02-01 15:27

    I saw this question and I wanted to remove 1 specific key, not a full method, so here's my suggestion:

    const originalObj = {wantedKey: 111, anotherWantedKey: 222, unwantedKey: 1010};
    const cleanedObj = Object.assign(originalObj, {unwantedKey: undefined});
    
    0 讨论(0)
  • 2021-02-01 15:28
    const { bar, baz, ...qux } = foo
    

    Now your object qux has all of the properties of foo except for bar and baz.

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