Looping through an object and changing all values

后端 未结 7 1591
庸人自扰
庸人自扰 2020-12-29 21:42

I\'m having trouble looping through an object and changing all the values to something else, let\'s say I want to change all the values to the string \"redacted\". I need to

相关标签:
7条回答
  • 2020-12-29 22:21

    Use a proxy:

    function superSecret(spy) {
      return new Proxy(spy, { get() { return "redacted"; } });
    }
    
    > superSecret(spy).id
    < "redacted"
    
    0 讨论(0)
  • 2020-12-29 22:23

    You can also go functional.

    Using Object.keys is better as you will only go through the object properties and not it's prototype chain.

    Object.keys(spy).reduce((acc, key) => {acc[key] = 'redacted'; return acc; }, {})

    0 讨论(0)
  • 2020-12-29 22:25

    This version is more simple:

      Object.keys(spy).forEach(key => {
        spy[key] = "redacted");
      });
    
    0 讨论(0)
  • 2020-12-29 22:33

    try

    var superSecret = function(spy){
      Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });
      return spy;
    }
    
    0 讨论(0)
  • 2020-12-29 22:37

    A nice solution is using a combination of Object.keys and reduce - which doesn't alter the original object;

    var superSecret = function(spy){
      return Object.keys(spy).reduce(
        (attrs, key) => ({
          ...attrs,
          [key]: 'redacted',
        }),
        {}
      );
    }
    
    0 讨论(0)
  • 2020-12-29 22:43
    var superSecret = function(spy){
        for(var key in spy){
              if(spy.hasOwnProperty(key)){
                   //code here
                   spy[key] = "redacted"; 
                }
         }
       return spy;    
    }
    
    0 讨论(0)
提交回复
热议问题