Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get values ​from JSON data only of specific keys contained in an array

Im trying to build in Javascript a Table of Nutritional Values, Quantity and Daily Percentage.
I’ve saved JSON data in this way:

data : [
{
"recipe": {
  "totalNutrients": {
   "ENERC_KCAL": {
    "label": "Energy",
    "quantity": 122.67497750000001,
    "unit": "kcal"
   },

   "K": {
    "label": "Potassium",
    "quantity": 255.9084202548212,
    "unit": "mg"
   },

   "FAT": {
    "label": "Fat",
    "quantity": 11.89368915,
    "unit": "g"
   },

   "ZN": {
    "label": "Zinc",
    "quantity": 0.328366321935265,
    "unit": "mg"
   },
 
   "FIBTG": {
    "label": "Fiber",
    "quantity": 3.609618250000001,
    "unit": "g"
   },

   "SUGAR": {
    "label": "Sugars",
    "quantity": 0.5078356,
    "unit": "g"
   }
  }
 }
}]

I want to get ENERC_KCAL, FAT and the others values in the array "KEYS" from JSON data.

keys = ['ENERC_KCAL', 'FAT', 'CHOCDF', 'FITBG', 'SUGAR', 'PROCNT', 'CHOLE', 'NA'];

valNut = data[0].recipe.totalNutrients;

Is there a way to accomplish the following instruction:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

energyValue = valNut.ENERC_KCAL.quantity + ' ' + valNut.ENERC_KCAL.unit

using instead the values of the array in a loop?

for(h=0; h<keys.length; h++){
  energyValue = valNut.keys[h].quantity + ' ' + valNut.keys[h].unit
}

P.S. Sorry for the bad english.

>Solution :

To do what you require you could loop through the keys using map() to build a new array of the matching totalNutrients key objects. Something like this:

let data = [{recipe:{totalNutrients:{ENERC_KCAL:{label:"Energy",quantity:122.67497750000001,unit:"kcal"},K:{label:"Potassium",quantity:255.9084202548212,unit:"mg"},FAT:{label:"Fat",quantity:11.89368915,unit:"g"},ZN:{label:"Zinc",quantity:.328366321935265,unit:"mg"},FIBTG:{label:"Fiber",quantity:3.609618250000001,unit:"g"},SUGAR:{label:"Sugars",quantity:.5078356,unit:"g"}}}}];
let keys = ['ENERC_KCAL', 'FAT', 'CHOCDF', 'FITBG', 'SUGAR', 'PROCNT', 'CHOLE', 'NA'];

let filteredNutrientData = keys.map(key => data[0].recipe.totalNutrients[key]).filter(v => v);
console.log(filteredNutrientData);

Note that the final .filter(v => v) is to remove the undefined values resulting from searching for a non-existent key in the totalNutrients object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading