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
}
}
var myString = "Item1";
var jsObject =
{
Item1:
{
"apples": "red",
"oranges": "orange",
},
Item2:
{
"bananas": "yellow",
"pears": "green"
}
};
var keys = Object.keys(jsObject); //get keys from object as an array
keys.forEach(function(key) { //loop through keys array
console.log(key, key == myString)
});
You could use a for loop, but you'd have to store the array of keys somewhere.
var myString = "Item1";
var jsObject =
{
Item1:
{
"apples": "red",
"oranges": "orange",
},
Item2:
{
"bananas": "yellow",
"pears": "green"
}
};
var keys = Object.keys(jsObject);
for (var i = 0; i < keys.length; i++) {
if (myString == keys[i])
console.log('match: ', keys[i])
}
Optionally, you can use for..in
to get the keys as well.
var myString = "Item1";
var jsObject =
{
Item1:
{
"apples": "red",
"oranges": "orange",
},
Item2:
{
"bananas": "yellow",
"pears": "green"
}
};
for (var key in jsObject) {
console.log(key, key == myString)
}