Ways to access elements and their associated values in a JavaScript Array

I'm facing a challenge with a JavaScript array where I need to extract teams (Team A, Team B) and organize them into one array while preserving their order. See below for the current output of the array, as well as the JS code provided and the expected outcome.

Current Array:

[
  {
    "Team A": 2,
    "Team B": 3
  }
]

JS Code:

 var retValue = [];  
var count = this.jsonArray.map((cv) => {
  var teams = cv["teams"].reduce((acc, team) => {
    acc[team["value"]] = team["text"];
    return acc;
  }, {});
  return cv["duty"].reduce((acc, duty) => {
    acc[teams[duty["parentId"]]] = acc[
      teams[duty["parentId"]]
    ]
      ? acc[teams[duty["parentId"]] + 1
      : 1;
    return acc;
  }, {});
});

retValue = Object.keys(count).map((cv) => count[cv]);
console.debug(retValue); //working


var getKeys = [];
getKeys = Object.keys(retValue); //not working

var getValues = [];
....

Expected Result:

[Team A, Team B] , [2 , 3]

Original JSON Data:

{
  "jsonArray": [{
    "teams": [

      {
        "text": "Team A",
        "id": 1,
        "value": 500,
        "parentId": 333
      },
      {
        "text": "Team B",
        "id": 2,
        "value": 600,
        "parentId": 444
      }

    ],
    "duty": [

      {
        "text": "Meetings",
        "id": 11,
        "value": 100,
        "parentId": 500
      },
      {
        "text": "Lunch",
        "id": 12,
        "value": 101,
        "parentId": 500
      },
      {
        "text": "Time Cards",
        "id": 13,
        "value": 102,
        "parentId": 600
      },

      {
        "text": "Parking",
        "id": 14,
        "value": 103,
        "parentId": 600

      },
      {
        "text": "Breakfast",
        "id": 15,
        "value": 104,
        "parentId": 600
      }
    ]

  }]
};

Answer №1

In my opinion, approaching the solution in this manner might work:

let result = [];
let counter = jsonArray.map((currentValue) => {
  let teamsMap = currentValue["teams"].reduce((accumulator, team) => {
    accumulator[team["value"]] = team["text"];
    return accumulator;
  }, {});
  return currentValue["duty"].reduce((accumulator, duty) => {
    let teamName = teamsMap[duty["parentId"]];
    accumulator[teamName] = accumulator[teamName] ? accumulator[teamName] + 1 : 1;
    return accumulator;
  }, {});
});

console.log(counter);  // an array containing team names and their respective duty counts.

let keys = Object.keys(counter[0]);

console.log(keys);  // an array of team names

let values = Object.values(counter[0]); 

console.log(values);  // an array displaying the duty counts

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

Vuetify Event Calendar

Currently, I am using the Vue calendar with Vuetify version 2.1.x. I am trying to retrieve the time from a specific slot when it is clicked like this: @click:time="test" <v-calendar ref="calendar" :locale="$i18n.locale" v-model="schedulerObj.calV ...

Eslint problem: no-duplicates Fixing issue: cannot load resolver "node"

After performing an update on my project (a SPA using VueJS and Quasar Framework) today with npm update, I am encountering difficulties running it. An error message no-duplicates Resolve error: unable to load resolver "node" keeps appearing in various mod ...

Navigation bar remaining fixed on mobile devices

I have been working on a bootstrap site at http://soygarota.com/blog/public After checking the code multiple times, I have added the bootstrap.min.css, bootstrap.min.js, and jQuery. However, for some reason, the header navigation is not collapsing when vi ...

Developing automation triggers for testing

Our QA team recently raised concerns about the difficulty of automating frontend testing due to our HTML looking uniform across different components. In response, I came up with a quick workaround: <template> <div :role="$options.name"> ...

Creating a dynamic components binder

Currently, I am utilizing Vue version 2.7 with Composition API and encountering a challenge. My goal is to dynamically render a component based on a reactive value. Below is the code snippet: const renderTab = ref('admin'); // later in the templa ...

Utilizing Vue.js for Keyboard Binding

I'm brand new to coding and Vue, and I've hit a roadblock in my project. I'm creating a JavaScript calculator that needs to be usable both with a mouse and keyboard. While I've managed to make it work with the mouse, I just can't ...

Obtain the data from a nested array

I'm facing a situation where I have the following code: var obj = { level1 : { level2 : 'value' } }; I also have another object: var returnData = { value: "level1.level2", anotherThing: "level1" }; The goal is to ...

Establishing communication between a master process and worker processes in Node.js: A guide to verifying bidirectional communication

After coming across this particular script from the node documentation, I tried to implement it for sending messages between Master and worker processes using cluster. However, upon running the script, I encountered an issue where I could not verify the me ...

Using the toggle method or IF statements in JavaScript to implement show and hide functionality upon clicking

I’ve been struggling with this issue for days now. It seems like I may have overcomplicated a simple piece of code. I'm trying to show some divs when a button is clicked, but I’m having trouble getting it to work properly. Initially, I used VAR.st ...

"Utilizing react.js allows for the direct access of DOM elements by the main parent component

Is there a way to trigger click events on deeply nested DOM elements within my component hierarchy without passing down callback functions to each individual component? I'm looking to execute these events from the top parent App component using EventT ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

Learn the steps to resolve pagination issues in React. When the first page loads, ensure all data is displayed properly. Click

Here is an excerpt from my code snippet: const Inventory = () => { const [products, setProducts] = useState([]); const [pageCount,setPageCount] = useState(0); //console.log(pageCount); const [page,setPage] = useState(0); const navigate = useNa ...

Incorporating components into a pre-existing webpage without utilizing npm

As a beginner in Vue.js and someone who primarily works in a traditional LAMP environment, I have noticed that the vue components I've attempted to use are not working as expected. Can anyone assist me with: Offering guidance on installing vue compo ...

Issue with MomentJS inBetween function consistently displaying incorrect results

I'm currently working on Vue Datatable and I have a specific requirement to search for records between two dates. I am using the moment.js library and the inBetween function to achieve this. Strangely, when I hardcode the dates, the function returns t ...

Switching Vue.js from the standalone build to the runtime-only build midway through a project?

Opted for the runtime-only version of Vue.js for a new project. I came across in the documentation that to switch to the standalone version, one must include an alias in webpack like this: resolve: { alias: { 'vue$': 'vue/dist/vue.js& ...

Adjust fancybox height using jQuery

I am working on a project where I need to display a fancybox containing an iframe from another domain. The iframe has dynamic content and its height may change based on the pages it navigates to or the content it displays. I have access to the code of the ...

Unable to generate a select element using the JSON data retrieved from an Ajax request

After making an AJAX call to fetch some JSON objects, I successfully retrieve them. However, I encountered an issue while trying to generate a select element from the returned JSON - it doesn't seem to create one. This is what my JavaScript looks lik ...

Generating a string indicating the range of days chosen

Imagine a scenario where there is a selection of days available to the user (they can choose multiple). The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday ...

The request has been unsuccessful with error code 405 in Nextjs version 14

I am currently working with NextJs version 14 and encountering a 405 error: GET http://localhost:3000/api/products 405 (Method Not Allowed) Uncaught (in promise) AxiosError products.js "use client" import { useState } from 'react'; ...

Interacting with a non-stringified object displayed in the browser console using TestCafe

Upon receiving a page that logs an object to the console, I encountered an issue when trying to access this object using getBrowserConsoleMessages(). The object appeared as the String "[object Object]" in the console, making it impossible for me to parse ...