Reputation: 21
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
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