score:4

Accepted answer

First, since you are new to JSON, a little terminology correction to help you out: JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.

Now for your question. You have two approaches:

  1. You can use a poly-fill for an upcoming ECMA 6 array method and future proof your answer
  2. Or you can roll your own solution using ECMA 5 functionality

The first solution would be to use the poly-fill provided in the documentation for find:

var countryData = data.find(function(element, index, array) {
  return element.Id === 'SWE';
});

countryData.Population // 9592552

The second method is basically recreating the poly-fill in a whatever manner you choose and if you choose that option I'll leave that up to you as an exercise to learn from.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

var data = [{
  "Id": "SWE",
  "Country": "Sweden",
  "Population": 9592552
}, {
  "Id": "NOR",
  "Country": "Norway",
  "Population": 5084190
}];

function display(e) {
  console.log("E", e);
  var countryData = data.find(function(element, index, array) {
    return element.Id === e;
  });
  console.log(countryData.Population);
}

display('SWE');

score:1

Just loop thru them until you see the right id.

for (var i in data) {
    if (data[i].Id == 'SWE') console.log(data[i]['Population']);
}

You could also use a while loop or regular for loop. Here every i "key" in data is tested, so each piece of data is data[i].


Related Query

More Query from same tag