$.grep 不与我一起过滤 JSON

$.grep not working with me for filtering JSON

尝试使用 grep,这样我就不会多次调用我的服务器来获取它创建的控件 -

$.ajax({
    type: "POST",
    url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
    data: '{Status: "' + Name + '", search: "' + SearchBox.text() + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    async: false,
    success: function (d) {
        var preparse = JSON.stringify($.parseJSON(d.d));
                    
        var data = $.grep(preparse, function (element, index) {
            return element.status.trim() == "Pending";
        });
        $("[id*=TextBox2]").text(preparse);
    }
});

如果我测试 preparse 变量,这将返回 JSON 格式的数据。

我不能 post JSON 因为它太多了,需要匿名。然而,作为示例,它 returns 类似于以下内容:

[{
    "Project ID": "18180",
    "OPRN": null,
    "Proj_Type": "2049",
    "CompleteDate": "2020-05-21T00:00:00",
    "SQFT": 2000,
    "State": "FL      ",
    "County": "Orange",
    "status": "Pending"
},
{
    "Project ID": "18180",
    "OPRN": null,
    "Proj_Type": "2049",
    "CompleteDate": "2020-05-21T00:00:00",
    "SQFT": 2000,
    "State": "SC",
    "County": "Orange",
    "status": "Pending"
},
{
    "Project ID": "18180",
    "OPRN": null,
    "Proj_Type": "2049",
    "CompleteDate": "2020-05-21T00:00:00",
    "SQFT": 2000,
    "State": "GA",
    "County": "Orange",
     "status": "Won"
}];

但是,当尝试 $.grep 时,我通过 data 变量得到以下结果:

[{
    {
        "P,r,o,j,e,c,t, ,I,D,",:, ",1,8,1,8,0,",
        ",O,P,R,N,",:, ,n,u,l,l,
        "P,r,o,j,_,T,y,p,e,",:, ,",2,0,4,9,",
        "C,o,m,p,l,e,t,e,D,a,t,e,",:, ,",2,0,2,0,-,0,5,-,2,1,T,0,0,:,0,0,:,0,0,",
        ",S,Q,F,T,",:, ,2,0,0,0,,
        "S,t,a,t,e,",:, ,",G,A,",
        "C,o,u,n,t,y,",:, ,",O,r,a,n,g,e,",
         "s,t,a,t,u,s,": ",W,o,n,,
    }];

正如评论中所指出的,您根本不需要做任何准备或准备您的回复。您提供的示例是 JSON,并且您的 AJAX 代码告诉 JS 期望 JSON 响应 (dataType: 'json'),因此在您的 success 回调中 d 已经是 JSON。简单地摆脱你的准备工作,你的代码就可以工作了:

let d = [
    {
        "Project ID": "18180",
        "OPRN": null,
        "Proj_Type": "2049",
        "CompleteDate": "2020-05-21T00:00:00",
        "SQFT": 2000,
        "State": "FL      ",
        "County": "Orange",
        "status": "Pending"
    },
    {
        "Project ID": "18180",
        "OPRN": null,
        "Proj_Type": "2049",
        "CompleteDate": "2020-05-21T00:00:00",
        "SQFT": 2000,
        "State": "SC",
        "County": "Orange",
        "status": "Pending"
    },
    {
        "Project ID": "18180",
        "OPRN": null,
        "Proj_Type": "2049",
        "CompleteDate": "2020-05-21T00:00:00",
        "SQFT": 2000,
        "State": "GA",
        "County": "Orange",
        "status": "Won"
    }
];

var data = $.grep(d, function (element, index) {
    return element.status.trim() == "Pending";
});

console.dir(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>