Home > database >  Matching ifferent forms of nested JS object / array data matching
Matching ifferent forms of nested JS object / array data matching

Time:02-22

I have the results of my MongoDB db query for two variables as follows :

foodelectricity [
  { food: 'dairy', electricity: 1 },
  { food: 'fruitAndVeg', electricity: 1 },
  { food: 'grains', electricity: 1 },
  { food: 'bakedGoods', electricity: 5 },
  { food: 'protein', electricity: 1 }
]

foodresults { bakedGoods: 1, dairy: 3, fruitAndVeg: 1, grains: 2, protein: 1 }

I need to multiyply the number values in foodresults times the electricity associated with that same item type in food electricity.

For example :

let helpValue = foodresults.bakedGoods = 1 * foodElectricity.food.bakedGoods = 5.

I not believe that MongoDB returns the array in the same order each time -- so some sort of key value matching is required.

I am having trouble figuring out how to find the helpValue.

Any help is deeply appreciated.

With thanks Karen

CodePudding user response:

You could make a copy of foodresults and then loop over foodelectricity array and multiply electricity with matching value from the results object.

const foodelectricity = [{"food":"dairy","electricity":1},{"food":"fruitAndVeg","electricity":1},{"food":"grains","electricity":1},{"food":"bakedGoods","electricity":5},{"food":"protein","electricity":1}]

const foodresults = {
  bakedGoods: 1,
  dairy: 3,
  fruitAndVeg: 1,
  grains: 2,
  protein: 1
}

 const helpValues = { ...foodresults }
 foodelectricity.forEach(({ food, electricity }) => {
   helpValues[food] *= electricity
 })
 
 console.log(helpValues)

  • Related