Remove value from object without mutation

后端 未结 8 771
天涯浪人
天涯浪人 2020-12-07 18:50

What\'s a good and short way to remove a value from an object at a specific key without mutating the original object?

I\'d like to do something like:



        
相关标签:
8条回答
  • 2020-12-07 19:31

    As suggested in the comments above if you want to extend this to remove more than one item from your object I like to use filter. and reduce

    eg

        const o = {
          "firstname": "Jane",
          "lastname": "Doe",
          "middlename": "Kate",
          "age": 23,
          "_id": "599ad9f8ebe5183011f70835",
          "index": 0,
          "guid": "1dbb6a4e-f82d-4e32-bb4c-15ed783c70ca",
          "isActive": true,
          "balance": "$1,510.89",
          "picture": "http://placehold.it/32x32",
          "eyeColor": "green",
          "registered": "2014-08-17T09:21:18 -10:00",
          "tags": [
            "consequat",
            "ut",
            "qui",
            "nulla",
            "do",
            "sunt",
            "anim"
          ]
        };
    
        const removeItems = ['balance', 'picture', 'tags']
        console.log(formatObj(o, removeItems))
    
        function formatObj(obj, removeItems) {
          return {
            ...Object.keys(obj)
              .filter(item => !isInArray(item, removeItems))
              .reduce((newObj, item) => {
                return {
                  ...newObj, [item]: obj[item]
                }
              }, {})
          }
        }
    
        function isInArray(value, array) {
          return array.indexOf(value) > -1;
        }

    0 讨论(0)
  • 2020-12-07 19:32

    For my code I wanted a short version for the return value of map() but the multiline/mutli operations solutions were "ugly". The key feature is the old void(0) which resolve to undefined.

    let o2 = {...o, age: 31, lastname: void(0)};
    

    The property stays in the object:

    console.log(o2) // {firstname: "Jane", lastname: undefined, age: 31}
    

    but the transmit framework kills it for me (b.c. stringify):

    console.log(JSON.stringify(o2)) // {"firstname":"Jane","age":31}
    
    0 讨论(0)
提交回复
热议问题