Read JSON from JavaScript array and search for values?

Massimo Scola
Massimo Scola used Ask the Experts™
on
I'm developing a Cordova app and one of the function is, that it can display orders.
I would like to retrieve all the orders when the app starts and put them into a JavaScript array:


var allOrders = [];			
this.getAllOrders = function() {
				var url = "http://137.108.92.9/openstack/api/orders?OUCU=" + oucu + "&password=" + password;
				/* Get the data */

				$.get(url, function (data) {
					var obj = $.parseJSON(data); // 
					if (obj.status == "success") {
						// was able to get the data successfully 
						// loop through all orders
								$.each(obj.data, function(i, item) {
                  console.log(item);
									app.allOrders.push(item);
                });
          };
				})
      }

Open in new window


The JavaScript array is populated with JSON objects.

How do I read JSON objects out of the array? For example, I would like to find out in which position the Order ID 71415 is.

      //Searches for an order ID
      this.searchOrderID = function(OrderID) {
        ???
      }

Open in new window


I would appreciate it if someone could give me an idea how to read json objects out of a JavaScript array. Searching for an order ID is one thing and then I would like to retrieve the picture URL for example .. I think once I know how to loop through the variable and then read the element ID, it should make it easier for me to implement the other functions.

Thanks for your help

Massimo
JSfiddle: https://jsfiddle.net/mscola75/ksqyem7g/2/



The JavaScript array with data
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Multitechnician
Top Expert 2014
Commented:
this.searchOrderID = function(OrderID) {
   for(var i=0; i<app.allOrders.length; i++) {
         if( app.allOrders[ i ].id == OrderID ) 
                  return i;
   }
   return -1; // NOT FOUND
}

Open in new window

Massimo ScolaSoftware Engineer

Author

Commented:
Thank you so much - very helpful answer!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial