JavaScript: Discovering similar property values within complexly nested arrays and objects

I am facing an issue with matching values from two JSON sources. While using the javascript find method, I have found that it works when the nesting of the "cities" array is one level more shallow (just an array of objects), but doesn't work with deeper nesting (an array of objects within an array of objects).

My goal is to iterate through the feeds[0].feed.details.place array and find the corresponding

cities.CountyPlaces.PlaceFIPSCode
value for each entry. I require the entire "place" object so that I can utilize any data within it for each match.

// console.log(feeds[0].feed.details.place);
// console.log(cities[1].CountyPlaces[2].PlaceName);
feeds[0].feed.details.place.map(async (arrItem, z) => {
  // console.log('arrItem: ', arrItem);
  const cityMatch = await cities.find((cityObject, i) => {
    // console.log(i, 'cityObject: ', cityObject);
    arrItem === cityObject.PlaceName;
  });
  if (cityMatch !== undefined) {
    // --> THIS IS WHERE I NEED TO MANIPULATE MATCHING DATA
    console.log(
      z,
      'cityMatch: ',
      arrItem,
      cityMatch.PlaceName,
      cityMatch.PlaceFIPSCode
    );
  } else {
    // there should be a defined match for every "place" and no else results
    console.log(z, '💥 cityMatch UNDEFINED', arrItem);
  }
});

Here is a simplified version of the data I am working with, showcasing the identical nesting structure:

const feeds = [
  {
    feed: {
      record: '0002',
      details: {
        county: ['Alameda'],
        place: ['Alameda', 'Berkeley', 'Oakland'],
      },
    },
  },
];
const cities = [
  {
    CountyName: 'San Francisco',
    CountyFIPSCode: '075',
    CountyPlaces: [
      {
        PlaceName: 'San Francisco',
        PlaceFIPSCode: '67000',
      },
    ],
  },
  {
    CountyName: 'Alameda',
    CountyFIPSCode: '001',
    CountyPlaces: [
      {
        PlaceName: 'Alameda',
        PlaceFIPSCode: '00562',
      },
      {
        PlaceName: 'Albany',
        PlaceFIPSCode: '00674',
      },
      {
        PlaceName: 'Berkeley',
        PlaceFIPSCode: '06000',
      },
      {
        PlaceName: 'Emeryville',
        PlaceFIPSCode: '22594',
      },
      {
        PlaceName: 'Oakland',
        PlaceFIPSCode: '53000',
      },
    ],
  },
];

Answer â„–1

If you want to narrow down the cities array by matching the CountyName with details.county[0] and then further filter the CountyPlaces based on whether the PlaceName is included in details.place, you can follow this JavaScript example:

const feeds = [
  {
    feed: {
      record: '0002',
      details: {
        county: ['Alameda'],
        place: ['Alameda', 'Berkeley', 'Oakland'],
      },
    },
  },
];

const cities = [
  {
    CountyName: 'San Francisco',
    CountyFIPSCode: '075',
    CountyPlaces: [
      {
        PlaceName: 'San Francisco', PlaceFIPSCode: '67000',
      },
    ],
  },
  {
    CountyName: 'Alameda',
    CountyFIPSCode: '001',
    CountyPlaces: [
      {
        PlaceName: 'Alameda', PlaceFIPSCode: '00562',
      },
      {
        PlaceName: 'Albany', PlaceFIPSCode: '00674',
      },
      {
        PlaceName: 'Berkeley', PlaceFIPSCode: '06000',
      },
      {
        PlaceName: 'Emeryville', PlaceFIPSCode: '22594',
      },
      {
        PlaceName: 'Oakland', PlaceFIPSCode: '53000',
      },
    ],
  },
];

const county = feeds[0].feed.details.county[0];
const places = feeds[0].feed.details.place;

const result = cities
  .filter(city => city.CountyName == county)[0]
  .CountyPlaces.filter(({ PlaceName }) => places.includes(PlaceName))
  
console.log(result)

Answer â„–2

If you need help with your issue, you can test out the solution below:

const matchingCity = cities.find((cityObj, i) => {
    // console.log(i, 'cityObject: ', cityObject);
    return cityObj.CountyPlaces.some(p=>p.PlaceName===arrItem)
   
  });

This will give you the matching place only

const matchingPlace = matchingCity.CountyPlaces.filter(p=>p.PlaceName===arrItem)[0]

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

What steps do I need to follow to create a controller component for a Form Element

I am trying to create a dynamic controller component in React Native, but I am facing issues with accessing errors. I am using "react-hook-form" for form elements. Here is my component: const { control, handleSubmit, formState: {errors}, ...

Tips for displaying just one dropdown when selecting an option in a jQuery menu

My menu is almost perfect, but I am facing one issue. When I click on .dropdown-toggle, only the closest ul should show, but in my code, all of them are shown and hidden simultaneously. What I want is that when I click on .dropdown-toggle, only the next ul ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

Trouble persisting values with Heroku due to variable issues

Here is a concise example: let value = null; const getValues = () => { fetch('/third-party-api') .then(res => res.json()) .then(data => { value = data; }) } getValues(); app.get("/values", async (req, res) ...

Pass data dynamically to router in ExpressJS

Within my app.js file, there are several variables defined: var user = "max"; Additionally, there is a route function set up like so: app.post('/register', user.postRegister); In the /routes/user.js file, there is a module function structured ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

What could be causing my getAsFile() method to return null?

Below is the code I have been working on: document.getElementById("Image_Panel").addEventListener('paste', (event) => { console.log("Initiating image paste - Step 1"); const clipboardData = event.clipboardData; // Checking ...

Grouping an array of arrays of objects

I am trying to group an array of objects based on the value of the first item below: const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"va ...

I'm attempting to grasp the concept of AngularJS's controllerAs notation

As I attempted to experiment with controllers by writing up a few examples, I encountered an issue where the controllers would not load. An error message appeared: firstController is not a function Upon doing some research, I discovered that Angular 1.3. ...

React Material Table - issue with data filtering accuracy

Currently in my React project, I am utilizing Material Table. While everything appears to be rendering correctly, the filtering and searching functionalities are not working as expected. To provide more context, below is a sample of the code: ht ...

Transferring a JSON document to an Express server with JavaScript

I've recently started learning JavaScript and I'm facing an issue with sending a JSON file to my server (Express) so that I can parse its contents and use them in the web application I'm developing. Here's my current setup: a JSON fil ...

The JavaScript function is designed to only accept whole numbers as input

Whenever I invoke a JavaScript function and pass along 4 parameters, it only functions properly if the fourth parameter consists of integers exclusively. Below is the code snippet for my onchange function: onchange="weekchange(this, <?php echo $i ?> ...

Remove an item from an array and keep it stored efficiently without generating unnecessary waste

I'm interested in finding a high-performance method for removing and storing elements from an array. My goal is to create an object pool that minimizes the need for garbage collection calls. Similar to how .pop() and .unshift() remove elements from a ...

Unable to locate an element on the webpage due to a JavaScript-based error, which then becomes hidden after a few seconds. (Registration form)

While completing a registration form, I encounter a hidden message after clicking on the register button. Struggling to locate this elusive element has been an ongoing challenge for me. Unfortunately, my attempts to find the element have been unsuccessful ...

How to use jQuery to dynamically add a variable to a request in Laravel 5.2

Is it feasible to append a variable to the Laravel cookie in the client using jQuery? Understandably, the Cookie is linked to the request during GET? Can you include a variable in the $request container in Laravel 5.2 using jQuery before initiating a GET ...

The web method within the aspx page is failing to execute

On page load, I am attempting to make an ajax request using the AngularJS $http service to fetch JSON data from a web method located in my User.aspx.cs page. The web method is defined as follows: [WebMethod] [ScriptMethod(ResponseFormat=ResponseForma ...

Show the result as "Content-Type: image/jpeg" on the webpage

I have a URL for an API request that automatically downloads and saves a QR code image from the browser. The Content-Type of the URL is application/jpeg, and its format looks like this: application(websiteURL)/egs?cmd=gen_qrcode&customer_id=123&n ...

There appears to be an issue with Google Analytics not generating __utm.gif requests, yet no error messages are

I'm encountering an issue with implementing Google Analytics. Despite extensive research, I haven't been able to find a resolution. My objective is to include the user's email address as a custom variable in Google Analytics. I have integra ...

Creating input fields using Vuejs

Currently, I am learning how to incorporate HTML content rendering in Vuejs. I'm experimenting with creating a small input component that is generated through the render function. Here is a snippet of what I have so far: export default { name: &qu ...