Jquery grep for json object array

I am trying to use grep to filter an array of json objects to search for an array and if the value of any of the keys # 2-6 is yes, the values ​​1 and 7 are returned.

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

Any help is VERY 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" } ] 
+6
source share
2 answers

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 β†’

+13
source

My version is very similar to the previous answer, I hope this 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 }; }); 
+1
source

Source: https://habr.com/ru/post/889991/


All Articles