且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从该数组中的值获取特定的JSON数组

更新时间:2023-01-16 23:09:01

首先,因为你是JSON的新手,有些术语修正可以帮助你:JSON是一个字符串,对象因此是 J ava S 脚本 O 对象 N 标签的缩写。您所拥有的内容通常称为POJO或 P 提供 O ld J avascript O 对象。他们是不同的。

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. 您可以为即将到来的ECMA 6阵列方法使用多重填充,
  2. 或者您可以使用ECMA 5功能卷自己的解决方案

第一个解决方案是使用poly -fill在 find

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');