jquery grep on json object array
Asked Answered
D

2

6

Im trying to use grep to filter a json object array so that the array is searched and if the value of any of keys #2-6 are yes, the value of keys 1 and 7 are returned.

The array is below -- in other words, if any of values for the 'location' keys are yes, the name and description are returned as list items.

Any help is VERY much appreciated.

[
    {
        "name": "name",
        "location1": "no",
    "location2": "no",
    "location3": "yes",
    "location4": "no",
    "location5": "no",
    "description": "description of services"
    },

    {   
    "name": "name",
        "location1": "yes",
    "location2": "no",
    "location3": "yes",
    "location4": "no",
    "location5": "no",
    "description": "description of services"        
    }
]
Disunion answered 7/6, 2011 at 19:11 Comment(0)
P
13

You will need to use both grep and map. If a is the array described above (but with name1, name2, etc), then after the following:

var b = $.grep(a, function(el, i) {
    return el.location1.toLowerCase() === "yes" 
           || el.location2.toLowerCase() === "yes" 
           || el.location3.toLowerCase() === "yes" 
           || el.location4.toLowerCase() === "yes" 
           || el.location5.toLowerCase() === "yes";
});

var c = $.map(b, function(el, i) {
    return {
        name: el.name,
        description: el.description
    };
});

c will contain [{"name":"name1","description":"description of services1"},{"name":"name2","description":"description of services2"}]

See example →

Prajna answered 7/6, 2011 at 20:39 Comment(4)
Wow - thank you, thank you- that's exactly what I was looking for -- and I havent used map or stringify before. The json data is coming from an external file and Im not exactly sure how to assign it to var a...?Disunion
$.getJSON('yourFile.json', function(data) { // in here data will be your array });Prajna
I know about two equal (==) signs but I am not sure about three equal (===). It is confusing. @Prajna Could you please explain it? or edit if it is a typo error.Loner
"===" simply means are the two sides of the argument truly equal? i.e without type coercion.Maurilia
B
1

My version is very similar to previous answer, I hope it helps:

    var checkYes = function(element) {

        var isYesInside = false;

        $.each(element, function(key, value) {
            if (value == "yes")
                isYesInside = true;
        });

        return isYesInside;
    };

    var yeses = $.grep(a, function(element, index) {
        return checkYes(element);
    });

    var finalArray = $.map(yeses, function(el, i) {
        return {
            name: el.name,
            description: el.description
        };
    });
Beacham answered 18/8, 2014 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.