Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep the JSON array contains in JavaScript or jQuery

Consider:

   var dummyArray =  [{
        "fname": "gali",
        "lname": "doe"
    }, {
        "fname": "john",
        "lname": "danny"
    }, {
        "fname": "joe",
        "lname": "dawns"
    }, {
        "fname": "liji",
        "lname": "hawk"
    }]

dummyArray = j$.grep(dummyArray, function(dt) {
             return (dt.fname== 'j');
});

How can I query the "fname" which contains letter "j" using the grep function?

like image 222
Ugesh Gali Avatar asked Jan 16 '23 15:01

Ugesh Gali


2 Answers

Using the ECMAScript 5 standard function Array.filter to only return the elements matching the predicate:

Starting with "j"

var j = dummyArray.filter(function(o) {
    return o.fname.charAt(0) === 'j';
});

or, containing "j"

var j = dummyArray.filter(function(o) {
    return o.fname.indexOf('j') >= 0;
});
like image 185
Alnitak Avatar answered Jan 23 '23 14:01

Alnitak


You can use indexOf:

dummyArray = $.grep(dummyArray, function(dt) {
    return dt.fname.indexOf("j") != -1;
});

DEMO: http://jsfiddle.net/Nhmwk/

like image 32
VisioN Avatar answered Jan 23 '23 15:01

VisioN