【问题标题】:jquery grep on json object arrayjson对象数组上的jquery grep
【发布时间】:2011-09-10 08:28:30
【问题描述】:

我尝试使用 grep 过滤一个 json 对象数组,以便搜索该数组,如果任何键 #2-6 的值为是,则返回键 1 和 7 的值。

数组在下面——换句话说,如果'location'键的任何值是yes,则名称和描述作为列表项返回。

非常感谢任何帮助。

[
    {
        "name": "name",
        "location1": "no",
    "location2": "no",
    "location3": "yes",
    "location4": "no",
    "location5": "no",
    "description": "description of services"
    },

    {   
    "name": "name",
        "location1": "yes",
    "location2": "no",
    "location3": "yes",
    "location4": "no",
    "location5": "no",
    "description": "description of services"        
    }
]

【问题讨论】:

    标签: jquery json getjson


    【解决方案1】:

    您需要同时使用grepmap。如果a 是上述数组(但带有name1name2 等),则在以下内容之后:

    var b = $.grep(a, function(el, i) {
        return el.location1.toLowerCase() === "yes" 
               || el.location2.toLowerCase() === "yes" 
               || el.location3.toLowerCase() === "yes" 
               || el.location4.toLowerCase() === "yes" 
               || el.location5.toLowerCase() === "yes";
    });
    
    var c = $.map(b, function(el, i) {
        return {
            name: el.name,
            description: el.description
        };
    });
    

    c 将包含[{"name":"name1","description":"description of services1"},{"name":"name2","description":"description of services2"}]

    See example →

    【讨论】:

    • 哇——谢谢,谢谢——这正是我想要的——而且我之前没有使用过 map 或 stringify。 json 数据来自外部文件,我不确定如何将其分配给 var a...?
    • $.getJSON('yourFile.json', function(data) { // in here data will be your array });
    • 我知道两个等号 (==),但我不确定三个等号 (===)。这令人困惑。 @mVChr 你能解释一下吗?如果是拼写错误,则进行编辑。
    • "===" 仅仅意味着参数的两侧真的相等吗?即没有类型强制。
    【解决方案2】:

    我的版本和之前的回答很相似,希望对你有帮助:

        var checkYes = function(element) {
    
            var isYesInside = false;
    
            $.each(element, function(key, value) {
                if (value == "yes")
                    isYesInside = true;
            });
    
            return isYesInside;
        };
    
        var yeses = $.grep(a, function(element, index) {
            return checkYes(element);
        });
    
        var finalArray = $.map(yeses, function(el, i) {
            return {
                name: el.name,
                description: el.description
            };
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-24
      • 2019-08-15
      • 2014-02-05
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      相关资源
      最近更新 更多