-2

Is there a way to locate data in an array by using value identifiers?

Example: In the object below, I want to do something similar to:

for(country in data.countries)
{
    if(country.name === "GB") {return-value-of-country.Clear;}
}

Object example:

 {
  "countries":[
    {
      "name": "GB",
      "Rain":" url1 ",
      "Clear":" url2 "
    }
    ...
  ]
} 
James
  • 20,957
  • 5
  • 26
  • 41
wraithie
  • 343
  • 1
  • 6
  • 19
  • `countries` here is an Array, so use index to select specific country before calling `.name` on top of it – Abhi Nov 28 '15 at 11:06

3 Answers3

0

Unless you're using ES6 or some external library there's not a great way to do it, something like:

var countries = data.countries,
    len = countries.length,
    match, i, country;

for (i = 0; i < len; ++i) {
    country = countries[i];
    if (country.name === 'GB') {
        match = country;
        break;
    }
}

if (match) {
    console.log(match.Clear);
}
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
0

To iterate over array you need for loop with index:

for(var i = 0; i<data.countries.length; ++i) {
    if(data.countries[i].name === "GB") {
        //your value is data.countries[i].Clear;
    }
}
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

If you are not using a library like underscore.

I would do something like:

var test = {
  "countries":[
    {
      "name": "GB",
      "Rain":" url1_gb",
      "Clear":" url2_gb"
    },
    {
      "name": "FR",
      "Rain":" url1_fr",
      "Clear":" url2_fr"
    },
    {
      "name": "DE",
      "Rain":" url1_de",
      "Clear":" url2_de"
    },

  ]
}

var getClearUrl = function(country) {
  for (var i = test.countries.length - 1; i >= 0; i--) {
    if (test.countries[i].name === country) {
      return test.countries[i].Clear;
      break;
    }
  };  

  return false;
}

var clearUrlGB = getClearUrl('GB');
console.log(clearUrlGB);
Clempat
  • 498
  • 4
  • 10