循环json数据并匹配到数组



我试图将数组与json中对象的值匹配,然后在div中提取该对象中的其他值,但它似乎只与json数据的最后一个对象匹配。我的数组是countryPath,它将根据我的URL在页面中具有值de。我想显示具有deurlCode的对象的详细信息

我的代码也是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>';
}
});

改为使用.find,如果满足条件,它将返回匹配的对象,并在循环的外部填充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>';

最新更新