110
rated 0 times
[
117]
[
7]
/ answers: 1 / hits: 42595
/ 8 Years ago, fri, november 18, 2016, 12:00:00
How do I compare a string to a JavaScript object's key? For example, here is a string and a JavaScript object. I want to compare the string (in this case, the value of myString is Item1) to a key in this JavaScript object (in this case, the keys are Item1 and Item2):
var myString = Item1;
var jsObject =
{
Item1:
{
apples: red,
oranges: orange,
},
Item2:
{
bananas: yellow,
pears: green
}
};
If I create a 'for' loop and run the contents of object through the loop, I want to compare the keys in this object to a string.
for (var x = 0; x < Object.keys(jsObject).length; x++)
{
if (myString == /* What do I put here to compare to grab Item1 or Item2? */)
{
// Do stuff
}
}
More From » string