Reputation: 185
I have an js object that is stored to variable
var data = {
"France":[
{
'population': "8M",
}
],
"Spain":[
{
'population': "18M",
}
]
}
and I have an input field that have some value (choosed from dropdown).
<input type="text" id="country1" onkeyup="myFunction()" placeholder="Select indicator" value="France">
I am trying to compare that value of the input with key of the object, and then if that value is equal to the key, to display population number. So far I tried to do like this
$( ".compare button" ).click(function() {
var c1 = $( ".first-country input" ).val(); //take value from input
var zemlja = Object.keys(data); //take all keys from object
var n = zemlja.includes(c1); //check if value is included in object
if (n) {
$(".country1-result h1").html(data.c1[0].population); //if value is included, add population number to result
}
});
And I got undefined. I figure it out that I can not take value if I put variable c1 instead of name of the key. If I put name of the key France, everything works fine, but if I put c1 variable that is equal to France, then it is not working. Any hint/help how to manage this to work.
Thanks.
Upvotes: 1
Views: 1134
Reputation: 68933
Since c1
is a variable, use bracket notation which will allow you to use property name as variable:
Change
$(".country1-result h1").html(data.c1[0].population);
To
$(".country1-result h1").html(data[c1][0].population);
var data = { "France": [{ 'population': "8M", }], "Spain": [{ 'population': "18M", }] }
function myFunction(){}
$(".compare").click(function() {
var c1 = $(".first-country").val(); //take value from input
var zemlja = Object.keys(data); //take all keys from object
var n = zemlja.includes(c1); //check if value is included in object
if (n) {
$(".country1-result h1").html(data[c1][0].population); //if value is included, add population number to result
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="country1" onkeyup="myFunction()" placeholder="Select indicator" value="France" class="first-country">
<input type="button" class="compare" value="Click" />
<div class="country1-result">
<h1></h1>
</div>
Upvotes: 1
Reputation: 7455
$( ".compare button" ).click(function() {
var c1 = $( ".first-country input" ).val(); //take value from input
var result = data[c1] ? data[c1][0].population : '';
$(".country1-result h1").html(result);
});
Upvotes: 0