Having trouble properly iterating through a Javascript JSON pull?

Here is the code that I am working with:

var input=require('./task.json');
const _ = require(`underscore`);
var dps = [];
for(var element in input) {
    for (var i=0;i>dps.length;i++){
        if(dps[i].Technician===input[element].Technician){
            console.log("name already exists");
            dps[i].count=dps[i].Count+1;

        }

    }
    dps.push({Technician: input[element].Technician, Count:0});
}


  console.log(dps);

This is how my task.json file is structured:

{{
        "TaskID": 35708,
        "TaskDate": "2011-06-20T00:00:00",
        "Technician": "UCH - Billy Metcalf"
    },
{
        "TaskID": 35708,
        "TaskDate": "2011-06-19T00:00:00",
        "Technician": "Edward F. Dawson"
    }
}

When I execute my file using node on data.js, I get a result like this:

[{Technician:'UCH - Billy Metcalf',Count:0},
{Technician:'Edward F. Dawson',Count:0}]

The main objective is to make sure that instead of always setting the count to zero, the program should go through the json file and if it encounters a duplicate entry in the new variable dps, it should increment the count. The new array dps should be unique without any repeating names. For instance, if there are 5 instances of "Edward F. Dawson", then

{Technician:'Edward F. Dawson',Count:5}

Answer №1

Give this a try. By going through the code step by step, it should become clear.

let data = require('./task.json');
const _ = require(`underscore`);
let technicians = [];
let foundMatch = 0;

for (let key in data) {
    foundMatch = 0;
    
    for (let i = 0; i < technicians.length; i++) {
        if (technicians[i].Technician === data[key].Technician) {
            console.log("Technician already exists");
            technicians[i].count = technicians[i].Count + 1;
            foundMatch = 1;
        }
        
    }

    if (foundMatch === 0) { // only if we didn't find a match!
        technicians.push({ Technician: data[key].Technician, Count: 1 });
    }
}

console.log(technicians);

Answer №2

Your task.json file contains invalid JSON syntax. To represent an array of objects, use square brackets [] instead of curly braces {}.

Once you format your JSON data into an array, you can execute the following code:

var input = require('./task.json');
const _ = require(`underscore`);
var dps = [];
input.forEach(function (element) {
    var found = dps.some(function (elem) {
      if (elem.Technician === element.Technician) {
          elem.Count = elem.Count + 1;
          return true;
      }
    });
    if (!found) {
      dps.push({Technician: element.Technician, Count: 1});
    }
});

console.log(dps);

If you prefer a more functional approach, you can also utilize the .reduce() method:

var dps = input.reduce(function (arr, currElem) {
    var found = arr.some(function (elem) {
      if (elem.Technician === currElem.Technician) {
          elem.Count = elem.Count + 1;
          return true;
      }
    });
    if (!found) {
      arr.push({Technician: currElem.Technician, Count: 1});
    }
    return arr;
}, []);

console.log(dps);

See the code in action below:

var input = [{
  "TaskID": 35708,
  "TaskDate": "2011-06-20T00:00:00",
  "Technician": "UCH - Billy Metcalf"
}, {
  "TaskID": 35708,
  "TaskDate": "2011-06-19T00:00:00",
  "Technician": "Edward F. Dawson"
}, {
  "TaskID": 35708,
  "TaskDate": "2011-06-19T00:00:00",
  "Technician": "Edward F. Dawson"
}, {
  "TaskID": 35708,
  "TaskDate": "2011-06-19T00:00:00",
  "Technician": "Edward F. Dawson"
}, ];
var dps = input.reduce(function (arr, currElem) {
    var found = arr.some(function (elem) {
      if (elem.Technician === currElem.Technician) {
          elem.Count = elem.Count + 1;
          return true;
      }
    });
    if (!found) {
      arr.push({Technician: currElem.Technician, Count: 1});
    }
    return arr;
}, []);

console.log(dps);

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

Displaying a list of text elements in a React component

Can someone help me figure out why my React app is not rendering a flat array of strings with the following code? {array.length > 0 ? ( <div> <h5>Email list</h5> <div style={{ paddingLeft: "50px", ...

Increasing the value of an external variable in MySQL Query through NodeJS

Currently, I am in the process of developing an API using NodeJS and MySQL. The main function of this API is to create new entries by executing queries one by one. In order to keep track of the successful execution of these queries, I have introduced a va ...

What is the process for constructing a regular expression (regex) in JavaScript to validate an id?

My validation requirements are relatively straightforward, but as someone who is new to regex, I am in need of quick assistance. The format should be either 1234567890 or 123456-7890, allowing for any number ranging from 0 to 9 and a total character length ...

Using Angular 4's ngModel can result in the transformation of data type from 'number' to 'string'

I am facing an issue with my Angular4 app where data captured from a form is stored in DynamoDB. The problem arises when an input field typed as 'text' is bound to a Typescript 'number' field, which seems to be converting the object val ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

Having trouble with Semantic UI Modal onShow / onVisible functionality?

Seeking assistance with resizing an embedded google map in a Semantic UI modal after it is shown. After numerous attempts, I have narrowed down the issue to receiving callbacks when the modal becomes visible. Unfortunately, the onShow or onVisible functio ...

Activate the jQuery click event by specifying the URL

On my webpage, I have a jQuery click function that loads multiple HTML pages into a specified div. I am looking to set specific URLs that will trigger this event, like test.com#about <script type="text/javascript"> $(document). ...

Issue with undefined object in ExpressJS PUT method

Attempting to utilize the PUT method for updating a record in my database, I encountered an issue with the object not being defined. ReferenceError: blogpost is not defined Following this tutorial for routing steps, I noticed that while the variable is d ...

Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user ...

Generate a visually dynamic representation of a live website page

I'm curious if it's possible to create a login page similar to the one shown in this image, using HTML, CSS, and Javascript. Instead of a traditional background image, I want the background to display the actual layout of another website, such a ...

Is there a way to navigate by scrolling, moving a centrally-positioned SVG along a path while also resizing the SVG?

After following the instructions in this post about resizing SVGs, I managed to keep the red square on the path while resizing the SVG. However, a new issue arises when scrolling down - the red square is not moving to stay positioned at the center of the w ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

When using JSX, it's important to wrap adjacent elements within an enclosing tag to avoid errors. Make sure to properly wrap the JSX tags to

import React, { useState } from 'react'; import ReactDOM from 'react-dom'; function DisplayData(props) { //creating the DataList const dataList = data.map(data => ( <><span>{data.name}</span> nbsp; <span> ...

How come when I click on the edit button, the selected data's model doesn't appear in the dropdown menu as I would like it to?

this is the function in my controller public function getModel($make_id = null) { $make_id = request()->make_id; $carsmodel = CarModel::where('make_id', $make_id)->orderBy('model', 'ASC')->get(); return re ...

Error validator failed for Mongo Db: Masekhta validation failed with error for _id field, expecting `_id`

I am struggling with creating simple scripts to add an object to MongoDB, and I keep encountering this error message: Error: Masekhta validation failed: _id: Error, expected _id I can't figure out why this is happening. My guess is that it might be r ...

Testing the Router.push function using Jest and ReactHere is a guide on how

As a beginner in unit testing, I find it challenging to grasp how I can effectively test or mock a push from a router. <Tab label="Members" alt="Members" onClick={() => Router.push('/members')}/> I am particularly concerned about testi ...

The $geoNear operator must be the initial stage in a pipeline to be valid

When performing an aggregation using nodejs as the server-side language, I encountered the error message $geoNear is only valid as the first stage in a pipeline. This is the Aggregation Object: [ { '$geoNear': { near: [Object], distanceFie ...

Draggable vue includes a Textarea HTML element that allows users to easily

The issue lies in implementing the draggable functionality on a textarea element. While the textarea allows text input and deletion, trying to select the text using pointer events triggers the dragging function instead, as shown in the image below: https ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...