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

removing a property from an object using AngularJS

Currently, I am working on a project involving AngularJS. The main goal of this project is to create a dynamic JSON generator using AngularJS. I have already developed the initial version and it works well. However, there is a minor issue with my applicati ...

Showing Text Information from a distant web server's jQuery.getJSON() script

I am currently working on a personal project that involves displaying data from a remote server. The HTML code I am using looks like this: <script> jQuery.getJSON("http://someurl.com/something.cgi? AJZ=1&STOCK=S", function(data) { if (data.inform ...

Unable to receive any response with AJAX requests

Welcome to my HTML page <html> <head> <title>Using AJAX</title> </head> <script type="text/javascript" src="ajax.js"></script> <body> <form action="searchItems.php" name="searchItem" method="p ...

I attempted to add the maatwebsite/excel package to my Laravel project, but encountered a error during installation

I attempted to add the maatwebsite/excel package to my Laravel project using the command: composer require maatwebsite/excel However, I encountered an error message that stated: Your requirements could not be resolved to an installable set of packages. ...

Configuring multiple views directories in Express fails to function as expected

Looking to define multiple views directories in Express. Working with Express version 4.16.3, Node.js version v10.15, and EJS version 2.5.9. app.set('views', [path.join(__dirname, 'views'), path.join(__dirname, 'public/static/&apo ...

How to ensure your content is always visible on Mobile Safari iOS 8 by making sure it stays

Although minimal-ui is no longer supported on iOS8, I've encountered an issue with some fixed content at the bottom of a webpage. The page height is set to 100vh to cover the entire viewport, but some of the content at the bottom is extending below t ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Utilize GroupBy in JavaScript to categorize JSON data and display it within an optgroup

I seem to be a bit disoriented. I have received this JSON data: [{ "id": "210", "name": "Name 1", "category": "Category 1" }, { "id": "187", "name": "Name 2", "category": "Category 1" }, { "id": "186", "name": "Name 3", ...

Issue with displaying current date and time dynamically (JavaScript/JQuery)

In order to create a real-time chat using websockets, I want to show the time of a message posted in this format: "% sec/min/hour/day now". After conducting some research, I came across two functions that I have modified : // Get the TimeStamp va ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

angular2 ngFor is not functioning properly

I'm having an issue where I cannot get textboxes to appear whenever a user clicks a button. I am attempting to achieve this using ngFor, but for some reason, the ngFor is not iterating as expected. Even after trying to change the array reference with ...

What is the best way to convert a circular JSON object to a string

Is there a way to stringify a complex JSON object without encountering the "Converting circular structure to JSON" error? I also need its parser. I am facing issues every time I try to use JSON.stringify and encounter the "Converting circular structure to ...

Passing a callback function through a prop in Vue.js

Currently, I have a component structured in the following way: <template> <div> <pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination> </div> </t ...

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...

grid causing images to display incorrectly in incorrect positions

My project consists of 3 component files and a CSS file, but I am facing an issue where the Tiles are slightly off in their positioning towards the top left corner. Although no errors are being thrown, upon using the view grid feature in Firefox, it is ev ...

Creating a regular expression to match special characters using JavaScript

I'm making an attempt to verify certain characters in my code. If the input field contains specific characters for each character, it will return true; otherwise, it will return false. function isChar(value) { //Creating a regex pattern to permit ...

modify a column in a database table when a different field is chosen

I am working on a basic table with 4 columns, two of which are dropdown menus with the classes "ddm1" and "ddm2". Here is what I am trying to achieve: Users should not be able to select from "ddm2" until they have selected an option from "ddm1". When ...

Unable to isolate segments of a string

Looking for a way to extract two different IDs from the following string: SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9: using Javascript. The regular expression being used is : ^SPList\:(?:[0-9A-Za-z\-]+ ...

Adjust the background hue and opacity when incorporating a "modal div"

Currently, I have a page where a hidden div appears at some point to display a form for inputting data. This could be considered a modal div. My goal is to darken the rest of the page and only allow interaction with this specific div. I want the backgroun ...

An HTML attribute with a blank value will not display the equals sign operator

jQuery can be used like this: $select.append('<option value="">All</option>'); This code appears to insert the element in HTML as follows: <option value>All</option> However, what is intended is to append the elemen ...