How can you multiply a value from an Object.entry for another key value inside a loop?

Viewed 88

I would like to add different worker values of each sector but multiply that value by another key:value property . This is a Vue.js composition API webapp.

export default {
  setup( props, {emit}) { 
  let data = reactive({

  let chosenCompanies:  [
        { id: 'Big',  workers: 250, clones: 9 },
        { id: 'Medium', workers: 75, clones: 2 },
        { id: 'Small', workers: 10, clones: 6 },
        { id: 'Individual', workers: 1, clones: 7}
      ]
});
const employedWorkers = () => {
  let employedworkersPrivate = 0;
  data.chosenCompanies.forEach(function(sector){
    for (const [key, value] of Object.entries(sector)) {
        if (key === 'workers') {
          employedworkersPrivate += parseInt(value)
       
  //  I need to multiply the number of workers per clones here, instead of just adding more workers 
  // can I get to the key 'clones' value here?

          }
    }
  })
  return employedworkersPrivate
}
}
}
2 Answers

No need to iterate over the entries - instead access only the exact two keys you need, the .workers and .clones.

let chosenCompanies =  [
        { id: 'Big',  workers: 250, clones: 9 },
        { id: 'Medium', workers: 75, clones: 2 },
        { id: 'Small', workers: 10, clones: 6 },
        { id: 'Individual', workers: 1, clones: 7}
      ]

const employedWorkers = () => {
  let employedworkersPrivate = 0;
  chosenCompanies.forEach(function(sector) {
    employedworkersPrivate += sector.workers * sector.clones;
  });
  return employedworkersPrivate;
};

console.log(employedWorkers());

You only need to iterate over chosenCompanies and access these values from each sector:

const chosenCompanies =  [
  { id: 'Big',  workers: 250, clones: 9 },
  { id: 'Medium', workers: 75, clones: 2 },
  { id: 'Small', workers: 10, clones: 6 },
  { id: 'Individual', workers: 1, clones: 7}
];
let employedworkersPrivate = 0;

chosenCompanies.forEach(function(sector){
  employedworkersPrivate += sector.workers * sector.clones;
});

console.log(employedworkersPrivate);

Related