Javascript request object

Ive got a JSON string that jumped to a javascript object

{ "results":[ { "id":"460", "name":"Widget 1", "loc":"Shed" },{ "id":"461", "name":"Widget 2", "loc":"Kitchen" }] } 

Is there any way to "query" this data in javascript so that I can search for the identifier 460 and return the name and loc (other than just scrolling the entire object)? I use jQuery and Prototypejs.

+6
source share
2 answers

Demo

JavaScript arrays have a built-in filter :

 var valuesWith460 = obj.results.filter(function(val) { return val.id === "460"; }); 

(to support older browsers you will want to grab the pad from the link above)

+16
source
 function getInfoByID( id ) var object = { ... }; for(var x in object.results) { if(object.results[x].id == id) { return [object.results[x].loc, object.results[x].name]; } } } 
+1
source

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


All Articles