简体   繁体   中英

How to filter the json data using jquery

I am working on asp.net mvc. I have a json response like,

[{"firstname":"xxx","lastname":"yyy","name":"zzz"},
{"firstname":"aaa","lastname":"bbb","name":"ccc"},
{"firstname":"zzz","lastname":"eee","name":"ddd"},
...]

Now i want to filter the above json response by name that startwith search criteria. I havebeen followed the following way,

var array=[];
array = jQuery.grep(jsondata, function (n,i) { return n.name.startsWith(searchstring); });

but i always get empty array. please guide me.

Probably jQuery.parseJSON() will help.

var data = $.parseJSON(<pass server json here>)[0], // 0 is used to match your example
    ret = [],
    rg = new RegExp('^' + search);

for (var i in data){
    if ( rg.test(data[i].name) ){ // '^' symbol is required.
        ret.push(data[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM