我有一个选择列表:
<select name="Country" id="Country">
<option value="US">United States</option>
<option value="DE">Germany</option>
</select>
还有一些json
[
{
"selection":"US",
"foo": "lorem"
},
{
"selection":"US",
"foo": "lorem lorem"
},
{
"selection":"DE",
"foo": "ipsum"
},
{
"selection":"DE",
"foo": "ipsum ipsum"
}
]
我想返回“selection”对象与选择列表中的值匹配的所有内容。
function load_Content() {
$.getJSON('./path/to.json', function(data) {
//this works, it gets the value from the select
var filter = $('#ForexCountry').val();
var myData = JSON.parse(//need to parse json into string?);
var countryData = $.grep(myData.filter, function (element,
index) {
return element.category == filter;
});
});
}
我似乎无法以正确的格式获得此信息。我需要:
你可以在这里使用.filter
。它将根据回调中的条件返回所有结果。此外,您不需要解析对JSON的响应,因为它已经是JSON。
var filter = $('#ForexCountry').val();
var countryData = data.filter(el => el.selection === filter);
如果你想使用grep方法,那就像是
function load_Content() {
$.getJSON('./path/to.json', function(data) {
var filter = $('#ForexCountry').val();
var matchingElements = $.grep(data, function(element){
return element.selection === filter;
});
});
}