0

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.

1
  • You would be better to filter the data server side, pass in your search query data as part of the JSON request.. maybe, I guess it depends on your UI requirements Commented Dec 5, 2012 at 16:41

1 Answer 1

1

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]);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

starts with condition not working here. is there any other way for that?
actually i have a variable 'name' in that search string will be stored. if(/^(search)/.test(data[i].name) condition working for for me. how to place varible in the regular expression in place of serach
RegExp constructor accepts strings as an arguments. Updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.