Search code examples
javascripttypescriptjavascript-objects

Loop through object containing boolean values


I have an object in key/value pairs that may contain boolean values. I need to evaluate the type of the value so I know what to return. So let's say I have an object that looks like:

{ 
 aKey: false,
 anotherKey: 4,
 yetAnotherKey: true
}

I want to loop through each key/value pair there and do something different depending on the type of the value. If I use Object.keys(options).map((key, index), it transforms the boolean values from true/false to 0/1, so I have no way of knowing that those are actually booleans.

What is the best way to go about this?


Solution

  • I think you just "oopsied" - you haven't even checked the value of the options object in your map function. The second parameter provided to an Array#map callback is always the index.

    Extending your code to check the type of the value in options:

    Object.keys(options).map((key, i, all_keys) => {
      let val = options[key];
      console.log(typeof val)
      ...
    });
    

    Consider reviewing the different methods of iteration / enumeration in JavaScript, e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

    How to iterate over a JavaScript object?