1

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?

user1795832
  • 2,080
  • 8
  • 29
  • 50
  • There shouldn’t be any transformation happening based on what you’ve pasted. If you use the builtin typeof function on the key you should be able to get what you need. – Antiokus Aug 20 '18 at 23:08
  • Can't help but say, if you don't know in advance what keys to expect or what types they will have, then you are dealing with a huge mess, and the inevitable outcome is a huge mess with more of the same piled on top... – Peter B Aug 20 '18 at 23:18

2 Answers2

2

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?

tehhowch
  • 9,645
  • 4
  • 24
  • 42
1

Your .map(key, index) is looping over the array ["aKey", "anotherKey", "yetAnotherKey"] and losing the values in options. Maybe something like this would work for you:

for( o in options ){
    console.log(o, options[o])
}

> aKey false
> anotherKey 4
> yetAnotherKey true
nbwoodward
  • 2,816
  • 1
  • 16
  • 24