0

我有一个像下面这样的json,

[
    {
        "id": "1",
        "freq": "1",
        "value": "Tiruchengode",
        "label": "Tiruchengode"
    },
    {
        "id": "2",
        "freq": "1",
        "value": "Coimbatore",
        "label": "Coimbatore"
    },
    {
        "id": "3",
        "freq": "1",
        "value": "Erode",
        "label": "Erode"
    },
    {
        "id": "4",
        "freq": "1",
        "value": "Madurai",
        "label": "Madurai"
    },
    {
        "id": "5",
        "freq": "1",
        "value": "Salem",
        "label": "Salem"
    },
    {
        "id": "6",
        "freq": "1",
        "value": "Tiruchirappalli",
        "label": "Tiruchirappalli"
    },
    {
        "id": "7",
        "freq": "1",
        "value": "Tirunelveli",
        "label": "Tirunelveli"
    }
]

我需要将它与这个 json 中的标签项进行模式匹配(即),如果我输入tiru,那么它必须生成其中包含 tiru子字符串的标签项。如果它是一个单项数组,我知道如何进行模式匹配和排序。这里我完全不知道,如何使用数组中的标签项进行模式匹配。是否有可能?。我需要使用 Pure javascript,有什么帮助吗?

4

2 回答 2

3

您可以使用 JavaScript 1.6 中引入的函数式数组方法,具体来说filter

var search = 'tiru';
var results = obj.filter(function(item) {
    var a = item.label.toUpperCase();
    var b = search.toUpperCase();
    return a.indexOf(b) >= 0;
});

如果您只想要标签,则可以使用map仅返回该属性:

var labels = obj.filter(function(item) {
    var a = item.label.toUpperCase();
    var b = search.toUpperCase();
    return a.indexOf(b) >= 0;
}).map(function(item) {
    return item.label;
});

本质上,filter这是一种可供任何人使用的方法,Array它返回一个Array只包含所提供函数返回 true 的那些成员的新成员。

于 2013-10-23T12:16:59.993 回答
1

JSON.parse() 将帮助将 jsonString 转换为 JsonObject 然后只需迭代对象使用 indexOf 进行模式匹配。

var jsonString = '[{"id": "1","freq": "1","value": "Tiruchengode","label": "Tiruchengode"},{"id": "2","freq": "1","value": "Coimbatore","label": "Coimbatore"},{"id": "3","freq": "1","value": "Erode","label": "Erode"},{"id": "4","freq": "1","value": "Madurai","label": "Madurai"},{"id": "5","freq": "1","value": "Salem","label": "Salem"},{"id": "6","freq": "1","value": "Tiruchirappalli","label": "Tiruchirappalli"},{"id": "7","freq": "1","value": "Tirunelveli","label": "Tirunelveli"}]';

    var jsonObjects = JSON.parse(jsonString);       
    var pattern = "tiru";

    for(var key in jsonObjects){
        var label = jsonObjects[key].label.toUpperCase();       
        if(label.indexOf(pattern.toUpperCase()) != -1){
            document.write(label+"<br/>");
        }
    }
于 2013-10-23T12:38:03.933 回答