0

我有以下 json 数据:

   "unit 251":{
      "path":"M256.57 475.46L251.00 478.71L248.15 478.14L245.46 474.81L253.62 468.11L254.07 467.73L256.10 470.18L256.12 470.20L257.48 470.41L257.48 470.41L258.49 471.59L259.64 472.92",
      "name":"unit 251",
      "status":"Avaliable",
      "color":"#006738",
      "size":"3200",
      "price":"300 000"
   }

虽然还有更多...而且我需要在 jquery 中添加一个可用的类,为了让我做到这一点,我需要一些如何按状态对数组进行排序。我目前正在尝试使用以下代码:

    //Filter By Status
    function filterUnitStatus(unitStatus){
        jQuery.grep(json['properties'], function(item){
            return item.status == unitStatus;

        });
    }
    //Filter By Status

    jQuery('#status').on('change', function(){
        var unitStatus = jQuery(this).val();
        filterUnitStatus(unitStatus);
    });

但我不知道我在做什么。

非常感谢任何帮助

4

2 回答 2

0

你没有从你的函数中返回任何东西,.grep()创建的是一个数组,所以返回它!此外,.grep()没有返回任何内容,我通过获取 JSON 对象键和迭代对其进行了修改:

//Filter By Status
function filterUnitStatus(unitStatus){
    return jQuery.grep(Object.keys(json), function(item) {
        return json[item].status == unitStatus;
    });
}

演示:http: //jsfiddle.net/ntTTp/

于 2013-09-12T13:07:33.720 回答
0

您的过滤器功能一开始没有返回任何内容,请将其更改为

function filterUnitStatus(unitStatus){
    return jQuery.map(obj, function(el){
        if (el.status == unitStatus) return el;
    });
}

jQuery.grep()只接受真正的数组作为参数。改为使用jQuery.map()。这将遍历数组或对象并返回一个包含所有匹配对象的数组。

tymeJV 提供的解决方案包含匹配对象的所有名称,这显然是 OP 想要的。将上述修改为

function filterUnitStatus(unitStatus){
    return jQuery.map(obj, function(el,id){
        if (el.status == unitStatus) return id;
    });
}

现在返回的数组将只包含匹配的键

见这里:http: //jsfiddle.net/ntTTp/2/

于 2013-09-12T13:07:35.560 回答