What is the best way to iterate through an Object.entry and multiply one value by another key value within a loop?

I am looking to enhance the functionality of my Vue.js composition API web application by calculating the total number of employed workers in different sectors. However, I want to multiply the number of workers by another key:value property instead of just adding them up.

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)
       
  //  In this context, I aim to factor in the number of clones per worker to get an accurate count instead of simply aggregating the workers
  // Is there a way to access the 'clones' value here?

          }
    }
  })
  return employedworkersPrivate
}
}
}

Answer №1

A more efficient approach is to access only the specific keys required, such as .workers and .clones, instead of iterating over all entries.

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

Answer №2

To retrieve the necessary information, simply loop through the chosenCompanies array and extract data from each corresponding sector:

const chosenCompanies =  [
  { id: 'Large',  workers: 300, clones: 5 },
  { id: 'Small', workers: 50, clones: 3 },
  { id: 'Micro', workers: 5, clones: 8 },
  { id: 'Startup', workers: 2, clones: 10}
];
let totalEmployedWorkers = 0;

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

console.log(totalEmployedWorkers);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Disabling Babel in Nuxt.js: A Step-by-Step Guide

I've come to the decision to eliminate Babel transpilation from my projects, as I no longer see the need to accommodate pre-ES6 era browsers. However, my search efforts have yielded no results on how to go about this. My Nuxt project is currently fill ...

Error! Element not found in cloned iframe #2460, promise unhandled

Can you help me troubleshoot this issue? This is the code I'm working with: const section = document.createElement("section"); const myHTMLCode = "<p>Greetings</p>"; section.insertAdjacentHTML("afterbegin", my ...

Exploring the Potential of Nested useFetch Functionality within Nuxt 3

Is there a way to achieve nested fetching in Nuxt 3? I have two APIs and the second API needs to be triggered based on a value returned from the first API. I attempted the code snippet provided below, but it is not working because page.Id is null when it ...

Is there a way to block the .load() function directly from the browser console?

I am looking to enhance the user experience on my website by dynamically loading certain content after login. This involves using a $.post(...) method to interact with a servlet that verifies the user's credentials, followed by a $.load(url) function ...

(RESPOND) Configuring a preset option for a Dropdown selection field

I am currently developing a frontend to demonstrate the behavior of a CRUD RESTful API. One specific requirement is that when the user selects the option "GET", the default value in the dropdown field labeled "Order-by" should be set to "Name". However, fo ...

Iterate through each entry in the database and identify and fix any duplicate records

In my form, I have a JSON array that includes the name and value of each input. I am attempting to add an "optionprix" attribute for each input with the "optionname" class based on the corresponding value of the input with the "optionprix" class. Here is ...

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

Iterate over an array utilizing the $.getJSON method for data retrieval

I have encountered an issue while using a for loop to iterate through an array of dates in a JSON request. The problem is that the loop seems to be fetching only the first item in the array each time it iterates, as if ignoring the variable i or being cach ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

The search for the view in the directory "/views" was unsuccessful in Express 4.0

I've been working on a project using Express 4.0 and the Express3-handlebars libraries for NodeJS. Below is the setup: app.set('views', path.join(__dirname, 'views/')); app.engine('hbs', hbs({defaultLayout: 'main&a ...

Struggling to determine whether an array contains data or is void in ReactJS?

In the state, I have an array and I set the default value of my state to an empty array []. After loading an API request, I need to display a loader until the data is ready. So, I am using a condition like this: (if the array length === 0, the loader wil ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Creating uniform line lengths with a ruler utilizing Fabric.js

I have a div that scrolls horizontally and contains a ruler div and a canvas where I draw horizontal lines of varying lengths. When drawing the lines, I want to ensure they are accurately measured against the ruler using JavaScript and CSS: var canvas = ...

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

What could be causing my newsletter form to malfunction on Amazon CloudFront?

I'm currently working with HTML on an Amazon EC2 instance (Linux free tier). I want to integrate CloudFront into my setup, but I'm encountering issues with my newsletter functionality. Despite not being an expert in AWS, I am struggling to unders ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Errors found during compilation when running the npm start command

After choosing to develop an app with React using VS Code, I initiated the process by running npm create-react-app ./, which was a success. However, when I proceeded to execute the command npm start, it resulted in compilation errors related to files suc ...

Tips for locating a value that differs from an item in a v-autocomplete box

I am using a v-autocomplete component: <v-autocomplete v-model="fromPrice" :items="listOfFromItems" dense solo label="from" hide-detail ...

Using VueJS Single File Components can cause issues with the example code for "Custom Popups" in the Google Maps API

Trying to implement a unique Google Maps popup following the provided documentation. After copying and pasting the official Google example code into a VueJS jsFiddle, the custom marker functions correctly as intended. It remains in the designated area eve ...