使用选择列表值返回json

问题描述 投票:0回答:2

我有一个选择列表:

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

我似乎无法以正确的格式获得此信息。我需要:

  1. 从下拉列表中获取国家/地区代码并将其存储为“过滤器”
  2. 获取json,过滤它只返回其“选择”与“过滤器”值相同的对象
  3. 返回数据
jquery json
2个回答
1
投票

你可以在这里使用.filter。它将根据回调中的条件返回所有结果。此外,您不需要解析对JSON的响应,因为它已经是JSON。

var filter = $('#ForexCountry').val();
var countryData = data.filter(el => el.selection === filter);

1
投票

如果你想使用grep方法,那就像是

function load_Content() {
    $.getJSON('./path/to.json', function(data) {
        var filter = $('#ForexCountry').val();
        var matchingElements = $.grep(data, function(element){
            return element.selection === filter;
        });
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.