0

I need to detect if the values ​​of an array are present in an object as a key

I tried this way

var color = {
             1: "Red",
             2: "Blue",
             3: "Yellow",
             4: "Violet",
             5: "Green",
             7: "Orange"
            };

var myColor = [3, 1];

for(const [key, value] of Object.entries(color)){

    var bgIco = (myColor.includes(key)) ? '[' + key + ']' + value + ' - Yes' : '[' + key + ']' + value + ' - No';

    console.log(bgIco);

}

But it always comes back no

If in the includes function I manually put a number in the object instead of the key variable then it works, what am I doing wrong?

2 Answers 2

1

Object properties are always strings (or symbols), even if they look like numbers when declaring them:

const obj = { 1: 'foo' };

const key = Object.keys(obj)[0];
console.log(key === 1);
console.log(typeof key);

So, map the myColor array to strings first:

var myColor = [3, 1].map(String);

Otherwise, the includes check will fail (since includes requires === - or SameValueZero - for a match to be found)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, it works perfectly, I knew it was something there, but I couldn't figure out what
0

If you want to check the array against the object seems simpler to iterate the array instead

var color = {
             1: "Red",
             2: "Blue",
             3: "Yellow",
             4: "Violet",
             5: "Green",
             7: "Orange"
            };

var myColor = [3, 1, 55];

for(let k of myColor){
   console.log(k, color.hasOwnProperty(k), /* OR */  k in color);      
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.