My goal: Implement a search function to show nutritional data pulled from USDA NDB API.
Status: Partial Success
The problem: USDA stuctured the object returned somewhat obnoxious. Referincing this screenshot: http://imgur.com/a/gOKdk Pizza has water at the first key value and Milk has energy.
My Question:
If I want to obtain the energy for example for all searches, how would I structure my ajax call?
$.ajax({
type: 'GET',
async: false,
url: 'http://api.nal.usda.gov/ndb/reports/?ndbno=' + ndbno[0] + '&type=b&format=json&api_key=',
success: function(results) {
food0 = results.report.food;
console.log(food0);
$("#jsGrid-nutrition").jsGrid("insertItem", {
name: food0.name,
kCal: food0.nutrients[1].measures[0].value,
servingSize: food0.nutrients[1].measures[0].label,
quantity: food0.nutrients[1].measures[0].qty,
carbs: food0.nutrients[4].value + food0.nutrients[4].unit,
fats: food0.nutrients[3].value + food0.nutrients[3].unit,
saturatedFats: food0.nutrients[3].value + food0.nutrients[3].unit,
protein: food0.nutrients[24].value + food0.nutrients[24].unit
});
You should loop your array and search for specific name
:
var energy = '';
$.each(food0.nutrient, function () {
if (this.name == 'Energy') {
energy = this.value;
return false; // == break; return true == continue;
}
});