Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
5



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)
}




[#60004] Thursday, November 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Mar 17, 20, 00:00, 4 Years ago
;