Rich C
Rich C

Reputation: 139

Match variable to JSON content and return data

I have a variable that contains a country name.

var country = 'belgium';

I have a JS data structure:

var countryCoords = {
  argentina: '56 100',
  belgium: '100 200'
}

How do I get the co-ordinates for Belgium?

Upvotes: 2

Views: 137

Answers (3)

Widor
Widor

Reputation: 13275

You can extract them using country as the key:

console.log(countryCoords[country]);

Upvotes: 0

Kyle
Kyle

Reputation: 22268

Objects support bracket notation and dot notation...

var country = 'belgium';

var countryCoords = {
  argentina: '56 100',
  belgium: '100 200'
}

countryCoords[country]; // '100 200'
countryCoords.belgium; // '100 200'

Upvotes: 5

Denys Séguret
Denys Séguret

Reputation: 382404

you get them with

var coords = countryCoords[country];

Upvotes: 3

Related Questions