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

Time:02-18

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:

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.

CodePudding user response:

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.

  • Related