遍历json数据并匹配数组

时间:2018-07-10 09:40:05

标签: javascript jquery json loops if-statement

我试图将数组与json中对象的值匹配,然后将该对象中的其他值拉到div中,但似乎它仅与json数据的最后一个对象匹配。 我的数组是 countryPath ,该数组将基于我的URL在页面中具有值 de-de 。我想显示具有 de-de

urlCode 的对象的详细信息

我的代码也是javascript,如果可能的话,我想将其转换为Jquery?

var data = [{
  "name": "Germany",
  "countryCode": "DE",
  "urlCode": "de-de",
  "standardPrice": "22",
  "standardFreeOver": "0",
  "standardTimes": "x"
},
{
  "name": "United Kingdom",
  "countryCode": "GB",
  "urlCode": "en-gb",
  "standardPrice": "30",
  "standardFreeOver": "x",
  "standardTimes": "x"
}];

data.forEach((o) => {
  if (countryPath.includes(o.urlCode)) {
    document.getElementById('output').innerHTML = '<div class="' + o.countryCode + '"><div class="header"><h2>' + o.name + '</h2><img src="https://gepi.global-e.com/content/images/flags/' + o.imgCode + '.png"></div><h3>STANDARD DELIVERY</h3><br><p>Price: ' + o.standardPrice + ' or free for orders over ' + o.standardFreeOver +
      '<br>Delivery Time:' + o.standardTimes + ' working days</p></div>';
  } else {
    document.getElementById('output').innerHTML = '<div><p>please choose a country</p></div>';
  }
});

1 个答案:

答案 0 :(得分:0)

改为使用.find,如果满足条件,它将返回匹配的对象,并在循环的{em> outside 中填充output。如果找到了对象,则使用该对象进行填充,否则,使用条件操作符使please choose a country保持代码更干燥:

const o = data.find(o => countryPath.includes(o.urlCode));
document.getElementById('output').innerHTML =
  o
  ? '<div class="' + o.countryCode + ...
  : '<div><p>please choose a country</p></div>';