Arjan van der Laan
Arjan van der Laan

Reputation: 21

How to iterate over the following array of objects inside another object in Javascript?

These are the objects and a simple function:

const getTotalYield = plants => {
    console.log(plants);
}

const corn = {
    name: "corn",
    yield: 3,
};
const pumpkin = {
    name: "pumpkin",
    yield: 4,
};
const crops = [
    { crop: corn, numCrops: 5 },
    { crop: pumpkin, numCrops: 2 },
];

I have to call it like this:

getTotalYield({crops})

output so far:
{
  crops: [ { crop: [Object], numCrops: 5 }, { crop: [Object], numCrops: 2 } ]
}

So how do I access the first object and then work with the properties in the array?

Upvotes: 0

Views: 37

Answers (1)

root
root

Reputation: 193

You can access your fields inside the object like this.
This snipet multiples the num of crops by the yields of each crop and them add it to the total yields.

const getTotalYield = plants => {
  let totalY =0;
  plants.forEach(function(element){
    totalY += (element.crop.yield)*element.numCrops;
  });
  console.log(totalY);
}

const corn = {
    name: "corn",
    yield: 3,
};
const pumpkin = {
    name: "pumpkin",
    yield: 4,
};
const crops = [
    { crop: corn, numCrops: 5 },
    { crop: pumpkin, numCrops: 2 },
];

getTotalYield(crops);

Upvotes: 1

Related Questions