Search code examples
javascriptfor-in-loophasownproperty

Using function to for-in loop through object to change values then return result


I'm building a function that uses a for-in loop to go through any object, change it's values (whether they be a number, string or boolean) to a single specific string, then output it. I've been through a bunch of existing questions which have helped me gain a general understanding of for-in loops. I've been trying to figure out how to make the function make the change then return the new values. Here's what I have so far:

var switcharoo = function(whateverObject){
  for (var i in whateverObject){
    if (whateverObject.hasOwnProperty(i)){
  alert(i + "redacted" + whateverObject[i]);
    }
  }
return whateverObject;
};    

I understand the framework I've set up for the function. I understand the structure of the for-in loop. I also understand the importance of the hasOwnProperty part. Now I'm lost... the

alert(i + "this is a string" + whateverObject[i]);

line, I can't wrap my head around. I got it from a question here on StackOverflow. The return whateverObject line is just my best effort to output the result. So how would I run through an object and change all the values to a specific string?

Bonus question: How would I tweak this function to search for true/false values and remove only the false ones?


Solution

  • The problem is... you're not changing anything at all :D

    alert just displays the value, but does nothing else.

    var switcharoo = function(whateverObject){
      for (var i in whateverObject){
        if (whateverObject.hasOwnProperty(i)){
          alert(i + "redacted" + whateverObject[i]);
    
          // Assign value to this key in whateverObject
          whateverObject[i] = 'redacted';
    
        }
      }
      return whateverObject;
    }; 
    

    How would I tweak this function to search for true/false values and remove only the false ones?

    Now for some advanced JavaScript. You can use Object.keys to get an array of an object's keys. Use that array to loop through all the keys in the object. You can then use reduce to construct an object with only the keys that don't have false values.

    function switcharoo(object){
      return Object.keys(object).reduce(function(allTrue, key){
        if(object[key] !== false) allTrue[key] = object[key];
        return allTrue;
      }, {});
    }