我试图使用grep过滤json对象数组,以便搜索数组,如果任何键#2-6的值为yes,则返回键1和7的值.
数组在下面 – 换句话说,如果’location’键的任何值为yes,则名称和描述将作为列表项返回.
很感谢任何形式的帮助.
[ { "name": "name","location1": "no","location2": "no","location3": "yes","location4": "no","location5": "no","description": "description of services" },{ "name": "name","location1": "yes","description": "description of services" } ]
解决方法
您需要同时使用grep和map.如果a是上面描述的数组(但是有name1,name2等),那么在以下之后:
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,i) { return { name: el.name,description: el.description }; });
c将包含[{“name”:“name1”,“description”:“services1”的描述},{“name”:“name2”,“description”:“services2的描述”}]