Reputation: 138
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?
Upvotes: 0
Views: 54
Reputation: 171698
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);
}
Upvotes: 0
Reputation: 371193
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)
Upvotes: 1