What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows:

[
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyName: "US"}, {type: "County", countyName: "US"}]},
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "German"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]},
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "Japan"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]},
]

This response consists of an array of objects, each containing country names in nested arrays. I am looking to extract all the county names into a single array, like this:

newNames = [US, German, Japan];

I attempted a solution but couldn't achieve the desired output. Can someone assist me with this? Thank you.

let newNames = this.selectedStateList.filter(item => item.countries.forEach(item => item.countries)).map(ele => ele.countries.forEach(item => item.countries))

Answer №1

To retrieve a list of unique countries, iterate through each `countries` object and store the data in a `Set`.

const data = [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyName: "US"}, {type: "County", countyName: "US"}]}, {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "German"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]}, {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "Japan"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]}, ],
      result = Array.from(data.reduce((r, {countries}) => {
        countries.forEach(({countyName}) => r.add(countyName));
        return r;
      }, new Set()));
console.log(result);

Answer №2

Utilize .map functions instead of .forEach - .map

transforms each item in an array, whereas
forEach` does not provide any return value.

Once you have an array of arrays containing country names, you can use .flat() to merge them - alternatively, combine them and apply flatMap.

const data = [
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}]},
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "German"}]},
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "Japan"}]},
];

const combinedData = data.flatMap(
  object => object.countries.map(
    country => country.countyName
  )
);
console.log(combinedData);

Answer №3

Do you think something like this would be effective?

const arr = [
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}]},
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "German"}]},
  {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "Japan"}]}
]

const result = arr.reduce((acc,val)=>{
    acc.push(val.countries[0].countyName)
    return acc
},[] )

console.log(result)

Answer №4

To extract the first entry of the countries element within each object in the given response (an array of objects), you can iterate over it as follows:

var data = [
    { type: "StateCountry", state: "AL", countries: [{ type: "County", countyName: "US" }] },
    { type: "StateCountry", state: "AL", countries: [{ type: "County", countyName: "German" }] },
    { type: "StateCountry", state: "AL", countries: [{ type: "County", countyName: "Japan" }] },
]
let result = []

for (const item of data) {
    result.push(item.countries[0].countyName)
}
console.log(result)

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

Leveraging Cheerio in Node.js to locate a precise value within an option tag

I'm facing difficulties in selecting the exact number (in this case 7) which is the value of the option. This is what I'm attempting: var $ = cheerio.load(html); console.log($('ProductSelect').val($("option:contains('7')").v ...

Adding icons to form fields based on the accuracy of the inputs provided

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Assignment 2 - Website Bui ...

Requiring three parameters, yet received four

Encountering an error in the dashboard.tsx file while trying to implement a line of code: "const { filteredEvents, stats, tableApps, formattedDate } = filterData(dataAll, Prefix, listApp, dateSelected);" The issue arose with the dateSelected parameter resu ...

Displaying images with Javascript when they are clicked

How can I make a speech bubble appear when the image of the person is clicked? <div> <p style="float: left;"><img src="person.png" border="1px"></p> </div> <script> function bubblespeech() { document.getEl ...

Tips for handling CSS loading delays with icons in OpenLayers markers

When using openlayers (v4.6.4) with font-awesome as marker icons, the icons do not display upon first load (even after clearing cache and hard reload). Instead, I see a rectangle resembling a broken character. It is only on the second load that they appear ...

Use jQuery's $.post method to validate the form field and prevent submission if there are any errors

I am trying to validate a form field on submit and block the submission if an ajax response message is returned. Below is the JS code I have: $('form.p_form').submit(function (){ var description = $.trim($('#f9').val()); var aa = $.pos ...

Event fails to trigger when attached to different elements

Currently, I have an onchange event linked to the input text box and an onclick event attached to a text link. Interestingly, when I click on the link after editing the textbox, the click event does not trigger - instead, the change event is fired. If you ...

The addClass() method seems to be malfunctioning following an ajax request

My current project involves setting up an AJAX call that is triggered when a user clicks on an anchor link. Once the AJAX operation is successful, I want to dynamically add a class to the specific anchor that initiated the call. The script itself seems to ...

How to use Ionic 3 to automatically scroll ion-scroll content all the way to the bottom

My ion-scroll component is experiencing some challenges <ion-scroll scrollY="true" style="height: 52vh;"> {{ text }} </ion-scroll> The content inside the ion-scroll keeps expanding, exceeding the designated height. Users can manually scroll ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

The response from Axios in NodeJs is displaying incorrect encoding

Having some trouble executing a REST call using Axios and receiving an unexpected response. try { const response = await axios.get("https://api.predic8.de/shop/products/"); console.log(response.data); } catch (error) { console.log(`[Error] -> ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type &apos ...

Error: Unable to access the 'prototype' property of an undefined object (inherits_browser.js)

After updating our app to a newer version of create-react-app, we started encountering the following error: This error seems to be related to inherits_browser.js, which is likely from an npm module that we are unable to identify. The line in error within ...

Use column formatting for the table's body section

I have written the code below in HTML to create a table. I am looking to apply a specific style to the table body elements in a column that has been assigned a CSS class, while excluding the header columns from this style application. As an example, I hav ...

The validation of DOM nesting has detected that a <td> element cannot be placed within an <a> element

When working on a React project with Material UI, I encountered an issue while trying to create a table. My goal was to make the entire row clickable, directing users to a page with additional information on the subject. Below is the snippet of code for th ...

Picture with predetermined size to occupy entire container

Seeking assistance! I am looking to pixelate an image after a jQuery event without using plugins like pixelate.js as they are not suitable for my project. Is it possible, through CSS or JavaScript, to automatically change the image to a smaller version wi ...

Ensuring a dependable detection of WebSocket connection status

I've been researching how to create a dependable method for recovering a WebSocket connection. After exploring various options, I discovered that one approach involves sending heartbeats (ping/pong) to the server and monitoring if the entire pong is ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

The module rxjs/operators cannot be located

When trying to import rxjs/operators in my Angular project, I use the following syntax: import { map } from 'rxjs/operators'; However, this results in the following error message: map is declared but its value is never read. Cannot find modu ...

What is the best way to display a unique modal on every tab?

I'm facing an issue where I am attempting to trigger a modal on each tab item, however the modal only opens on the initial tab. Clicking on any other item results in the modal opening on the first tab instead. Additionally, when I add new items, I am ...