Add values to each entry in a subarray

let b = [];
this.state.sidejobs.forEach((user) => {
  console.log(user);
  if (!b.hasOwnProperty(user.jobworker)) b[user.jobworker] = 0;

  b[user.jobworker] += user.duration;
});

I have a query regarding splitting and adding durations in entries where a jobworker has an array with two IDs. How can I achieve this?

Name          ID        Total Hours
Mike Smith    281           5
            284,281         5
John Doe      284           21
Chris Smith   283           23

Answer №1

   const workers = [];
    this.state.sidejobs.forEach((user) => {
      var jobWorkers = user.jobworker.toString().split(",");
      for (var i = 0; i < jobWorkers.length; i++) {
        var individualWorker = jobWorkers[i].trim();
        if (!workers.hasOwnProperty(individualWorker)) workers[individualWorker] = 0;
        workers[individualWorker] += user.duration;
      }
    });

Answer №2

Before we proceed, let's clarify whether b is an array or an object in your code. Are you using it as both? It seems like you intended for it to be an anonymous object.

let b = {};

It would also be beneficial to understand the precise structure of user.jobworker (you can use "JSON.stringify(user.jobworker)" to check). For now, let's assume that the user object has the following structure:

{
 name: "Mike Smith",
 id: 281,
 duration: 5,
 jobworker: [284, 281]
}

If this is accurate, you can achieve what you need by doing the following:

let b = {};
this.state.sidejobs.forEach((user) => {
  for (var i = 0; i < user.jobworker.length; i++) {
    if (!b.hasOwnProperty(user.jobworker[i])) b[user.jobworker[i]] = 0;
    b[user.jobworker[i]] += user.duration;
  }
});

If user.jobworker actually consists of a comma-delimited string of ids (e.g., user.jobworker = "284,281"), then you'll need to split the string first:

this.state.sidejobs.forEach((user) => {
  var jobworkers = user.jobworker.split(",");
  for (var i = 0; i < jobworkers.length; i++) {
    var worker = jobworkers[i].trim();
    if (!b.hasOwnProperty(worker)) b[worker] = 0;
    b[worker] += user.duration;
  }
});

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

Utilize the parsing functionality in three.js to extract JSON geometry data

After exporting a model from Blender using the three.js exporter and successfully loading it with the JSONLoader, my next challenge is to store the JSON information in a variable and parse it to display the model without having to load an external file. T ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

Block-level declarations are commonly used in TypeScript and Asp.net MVC 5

In my asp.net mvc5 project, I decided to incorporate TypeScript. I created an app.ts file and installed the nuget-package jquery.TypeScript.DefinitelyTyped. Here is a snippet of the app.ts code: /// <reference path="typings/jquery/jquery.d.ts"/> cl ...

Error: Unable to execute function on blog mapping

I am facing an issue with my app where it fails to detect objects. Every time the component in my app calls ".map", I encounter an error message. I have double-checked that index.js is passing props correctly. Can anyone explain why this problem is occurri ...

Obtaining data from a Nested Json file in Angular 5

Encountering difficulties retrieving data from nested JSON. Error: 1. <h3>{{sampledata}}</h3> displaying [object Object] 2. <p>{{sampleDataModel.Title}}</p> ERROR TypeError: Cannot read property 'Title' of undefined ...

Emulate a Click Using Pure JavaScript

I am looking to add a click event to my custom dropdown, which replaces a SELECT element. The purpose of this click event is to trigger the corresponding OPTION item when an LI element is clicked. It seems like Woocommerce uses some JavaScript or PHP func ...

What are some methods to maintain consistent height for each list item in an unordered list on small screens like mobile devices?

While vh works well for larger screen sizes such as laptops, it may not maintain the height of the li on smaller devices like mobiles. Is there a better approach than relying on media queries to achieve responsiveness across different screen sizes? ...

Use npm to import a module from the same index.js file that the current file is exporting from

Imagine a scenario where I have developed an npm package called @myscope/blurfl containing two classes: A, defined in A.js, and B, defined in B.js. Both classes are re-exported through blurfl/index.js: @myscope/ blurfl/ A.js B.js ...

Combining THREE.Sprite with fog or utilizing THREE.ParticleSystem with an array of texture maps

Currently attempting to create a particle system using Sprite, however, encountering an issue where Sprite does not appear to respond to the "fog" parameter, meaning it does not fade away with distance. While ParticleSystem does adhere to the fog parameter ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Delegating events after removing a class

I have a button element with the 'next' data attribute <button data-button='next' class="disabled">next</button> When I remove the disabled class to activate it, the click event doesn't trigger as expected $("[dat ...

The problem of having an undefined state in Vuex arises

https://i.stack.imgur.com/52fBK.png https://i.stack.imgur.com/GcJYH.jpg There is an error occurring: TypeError: Cannot read property 'state' of undefined ...

Objective-C's implementation of arrays in the style of C, Java, and other programming

Although Apple prefers using NS objects instead of primitive types, I require the functionality of an array for direct access to items at specific indices. It's challenging to find tutorials or resources on how to use basic primitive arrays due to thi ...

NgModel fails to properly bind value with dynamically generated checkbox inputs

When I click on the "edit" button in a row, a dynamically created form wrapped in a table appears. This form contains conditionals that display inputs when the row is being edited. The type and binding of these inputs are dynamic. Here is an example: < ...

Issue with Angular router failing to load the correct component

As a novice with Angular, I have the following routes set up. app.routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { FrameComponent } from './ui/frame/frame.compon ...

Display elements on hover of thumbnails using CSS

I'm struggling with the logic of displaying images when hovering over corresponding thumbnails using only CSS. If necessary, I can do it in JavaScript. Here's my latest attempt. <div id='img-container' class='grd12'> ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

Running and halting multiple intervals in Javascript - a guide

Imagine a scenario where I am setting up 3 intervals with times of 500ms, 1s, and 1.5s. When I click on the button for the 500ms interval, I want to stop the other two intervals and only run the 500ms one. The same goes for clicking on the 1s or 1.5s butto ...

Create an HTML table row that includes a value along with its related sibling and parent values

I need to create an HTML table that compares segments in a JSON object. The format should display the segments along with their measures organized by domain group and vertical: ------------------------------------------------------------------------------ ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...