Determine the absent information by comparing two JSON objects with JavaScript

Two JSON objects, counties and ctyIndem, are at hand. The counties object contains all the counties in a specific US State, while ctyIndem holds information about indemnities paid in that State by county, excluding those with no payments made. My task is to iterate through both JSON objects, and if a county is missing from ctyIndem, I must add the missing information from counties.

JavaScript Code:

var counties = [{
    FIPS: 1001,
    County: "Autauga",
    State: "ALABAMA"
    }, {
    FIPS: 1003,
    County: "Baldwin",
    State: "ALABAMA"
    }, {
   FIPS: 1005,
   County: "Barbour",
   State: "ALABAMA"
   }, {
   FIPS: 1007,
   County: "Bibb",
   State: "ALABAMA"
   }, {
   FIPS: 1009,
   County: "Blount",
   State: "ALABAMA"
   }, {
   FIPS: 1011,
  County: "Bullock",
  State: "ALABAMA"
  }];

  var ctyIndem = [{
  Year: 2015,
  State: "ALABAMA",
  id: 1001,
  County: "Autauga",
  Indem: 50
  }, {
  Year: 2015,
  State: "ALABAMA",
  id: 1003,
  County: "Baldwin",
  Indem: 200
  }, {
  Year: 2015,
  State: "ALABAMA",
  id: 1005,
  County: "Barbour ",
  Indem: 1501
  }];


  counties.forEach(function(a, v) {

  if (a.FIPS == ctyIndem[v].id) { 
    console.log(ctyIndem[v].id); 
   } else {

   var temp = [];
       temp.push({
       Year: ctyIndem[0].Year,
       State: a.State,
       id: a.FIPS,
       County: a.County,
       Indem: 0
      });
    Array.prototype.push.apply(ctyIndem, temp);
     }

     });

    console.log(ctyIndem);

An issue arises when iterating through the arrays and encountering a point where the county FIPS and id do not match. I am unsure of what action to take in such instances, resulting in a Uncaught TypeError: Cannot read property 'id' of undefined error since there is no match. Thank you for any assistance.

Answer №1

It seems like your searching logic needs some adjustments. Currently, it only checks if the element at the same index in the ctyIndem array has a matching id. However, since the indexes in the two arrays don't align perfectly, you should search the entire array instead.

An effective approach to solve this issue is by creating an object with keys that correspond to the IDs you are looking for. This way, you can easily check if a specific ID exists using a.FIPS as the index.


var ctyIds = {};
ctyIndem.forEach(function(c) {
    ctyIds[c.id] = true;
});

counties.forEach(function(a) {
    if (!ctyIds[a.FIPS]) {
        ctyIndem.push({
            Year: ctyIndem[0].Year,
            State: a.State,
            id: a.FIPS,
            County: a.County,
            Indem: 0
        });
    }
});

Answer №2

Before proceeding with your loop, it is important to verify the existence of ctyIndem[v].

// Check if ctyIndem[v] exists
if (ctyIndem[v] && a.FIPS == ctyIndem[v].id) {
  console.log(ctyIndem[v].id); 
 } else {

Answer №3

To start, create a flat array containing only the IDs from ctyIndem. By utilizing the Array.filter function, you can produce an array of counties that are absent from the list of IDs. Subsequently, insert a new object for each missing county:

    var indemnityIds = ctyIndem.map(function (c) { return c.id });

    var missingCounties = counties.filter(function (cnty) {
      return indemnityIds.indexOf(cnty.FIPS) === -1;
    });

    missingCounties.forEach(function (cnty) {
      ctyIndem.push({
        id: cnty.FIPS,
        State: cnty.State,
        County: cnty.County
      });
    });

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

Don't allow users to switch views without saving their changes

We are working with a Backbone.js application that presents various forms to users. Our goal is simple: if a user navigates away from the page without saving the completed form, we need to show a confirmation dialog. When dealing with traditional forms, i ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

The player remains unchanged

Hi, I am currently working on my app to update a player's age. To start off, I have added three players: const playerOne = store.dispatch(addPlayer({ firstName: 'Theo', lastName: 'Tziomakas', position: 'Goakeeper ...

Learn how to utilize interpolation within an *ngIf statement in Angular 2 in order to access local template

Consider the following scenario; <div *ngFor="item of items; let i = index;"> <div *ngIf="variable{{i}}">show if variable{{i}} is true</div> </div> Suppose I have variables named "variable0", "variable1",... Is there a way to ac ...

Do individual JavaScript script tags operate independently of one another in terms of error handling?

My main goal is to establish a connection to my server using websockets and send messages to the browser for remote page reloads. I want to ensure that this code runs independently of any other errors on the page, allowing me to remotely refresh the page i ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...

What is the best way to retrieve the value from a React Img element?

I am having an issue with receiving 'undefined' from the console.log in 'handleClickVideo'. How can I properly extract the value when clicking on a video? I attempted using a div as well, but since div does not have a value property, it ...

Leveraging jQuery for Adding Text to a Span While Hovering and Animating it to Slide from Left to

<p class="site-description">Eating cookies is <span class="description-addition"></span>a delight</p> <script> var phrases = new Array('a sweet experience', 'so delicious', 'the best treat', ...

Using Node.js to download files with like wget, unzip them, and convert them to JavaScript without saving to

Currently, I am working on a script for a nodejs/express server-side application using the libraries request, unzip, and xml2js. The goal of this script is to fetch a zip file from a specified URL, extract an XML file from it, and then parse that XML into ...

Adding a Protocol to a Socket Connection in Xcode and Transmitting JSON Data

As a beginner in Xcode, I am currently working on implementing the functionality of connecting to a signalling server using an example from GitHub. The challenge is that this signalling server only accepts connections if a protocol is set. Is there a way ...

Exploring PrimeNG's method for expanding and collapsing groups

I'm attempting to incorporate two buttons that can be used to either expand or collapse all the groups in my code utilizing primeNG. Below is the functioning code: PLUNKER <p-dataTable [value]="data" sortField="room" rowGroupMode="subheader" grou ...

The ajaxStart() and ajaxStop() methods are not being triggered

I'm currently working on a Q/A platform where users can click on specific questions to be redirected to a page dedicated for answers. However, when a user tries to answer a question by clicking the "Answer" link, certain background processes such as ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

Extract content from an HTML form within a specific cell using Cheerio

A sample HTML table is displayed below: <tr class="row-class" role="row"> <td>Text1</td> <td> <form method='get' action='http://example.php'> <input type='hidden' ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

Where within Video.js can I modify the color of the large play button when the cursor hovers over the video?

After successfully changing the SCSS $primary-background-color to orange using the video.js default skin editor (CodePen), I encountered an issue. Whenever I hover my mouse cursor over the video, the big play button background reverts to its default grayis ...

What is the best way to style the header of a table when scrolling in CSS?

Currently, I am facing an issue with applying the top CSS property to the thead element of a table while scrolling. I have attempted various methods but have been unsuccessful in achieving the desired outcome. Initially, I used the scroll event, however, ...

Troublesome CSS conflicts arise when using minified assets with AngularJS and Webpack

After transitioning my Angular project to the Webpack build system, I encountered issues with Angular Dependency Injection in the JS source code. Surprisingly, now I am facing JS errors that are targeting CSS files, leaving me completely bewildered about w ...

Capture line breaks from textarea in a JavaScript variable with the use of PHP

I need help with handling line breaks in text content from a textarea. Currently, I am using PHP to assign the textarea content to a Javascript variable like this: var textareaContent = '<?php echo trim( $_POST['textarea'] ) ?>'; ...

CAUTION: Handled [org.springframework.web.HttpMediaTypeNotSupportedException: Unsupported content type 'application/json']

https://i.stack.imgur.com/rHf7m.pnghttps://i.stack.imgur.com/GMCGT.pnghttps://i.stack.imgur.com/dyIOS.pngHello everyone, I could use some guidance on solving a problem I'm encountering while trying to consume a REST web service. Below is the code snip ...