简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM