我试图将一个数组与我的 json 中的一个对象的值相匹配,然后将该对象中的其他值拉到一个 div 中,但它似乎只与我的 json 数据的最后一个对象相匹配。 我的数组是 countryPath,根据我的 URL,它将在页面中具有值 de-de。我想显示 urlCode 为 de-de
的对象的详细信息我的代码也是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>';
关于javascript - 遍历 json 数据并匹配到一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51261918/