Uncovering unique data points within nested arrays in JavaScript using GraphQL

After receiving GraphQL results, I am faced with a challenge to process them using JavaScript

{
  "data": {
    "shoeStyleColor": [
      {
        "id": 1,
        "shoeInventories": [
          {
            "id": 1,
            "qty": 2,
            "size": 6.5
          },
          {
            "id": 2,
            "qty": 2,
            "size": 9
          }
        ]
      },
      {
        "id": 2,
        "shoeInventories": [
          {
            "id": 5,
            "qty": 3,
            "size": 8
          },
          {
            "id": 6,
            "qty": 1,
            "size": 9
          }
        ],
      }  
    ]
  }
}

I aim to extract a unique list of sizes like this... [6.5,8,9]

[...new Set(products.data.shoeStyleColor.map(x => x.shoeInventories.map(y => y.size)))]    

However, the output is not as expected: [6.5,9],[8,9]

What steps should be taken to filter the entire array based on a selected size, for example, 9? Any suggestions?

Answer №1

Consider trying out the flatMap() method

const products = {"data":{"shoeStyleColor":[{"id":1,"shoeInventories":[{"id":1,"qty":2,"size":6.5},{"id":2,"qty":2,"size":9}]},{"id":2,"shoeInventories":[{"id":5,"qty":3,"size":8},{"id":6,"qty":1,"size":9}]}]}}

const result = [...new Set(products.data.shoeStyleColor.flatMap(x => x.shoeInventories.map(y => y.size))]    

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

What could be causing the discrepancy in results between the first and second methods?

Implementing Weather Icons: const getWeatherIcon = (iconParameter) => { const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png` return <img src={icon} alt={iconParameter} /> } <div className="weathericon"> ...

The challenge of Angular form data binding

I'm encountering an issue with binding an input box to a controller in Angular. Despite following tutorials, the model never updates when I access the property or check the scope using AngularJS Batarang. Upon form submission, $scope.licenceKey remai ...

What is the reason behind only the initial click boosting the vote count while subsequent clicks do not have the same

In this snippet of code: //JS part echo "<script> function increasevotes(e,location,user,date,vote) { e.preventDefault(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState ...

How can jQuery grep be used with dual arrays?

Could it be a problem with my syntax, or am I completely off track with my approach here? I'm working with two arrays that store attributes selected by the user. I'm then attempting to filter a JSON file using $.grep() to find pillows that match ...

Disappearing a menu list while zooming in on a page: The art of vanishing navigation

[QUESTION] Is there a way to make the Menu List disappear when zooming in on a webpage? For example: <-- Normal Page [No Zoom] --> [Logo] Profile Gallery Guestbook <-- Zoom In 120% --> [Logo] Profile Guestbook <-- Zoom In 150% --> ...

Guidelines on how to retrieve information from an AJAX request in PHP

I am in the process of developing an application that involves calling a JS function in PHP like this: $data = "<script>JSFunction();</script>"; The JSFunction is defined as follows: function JSFunction(){ $.ajax({ type: 'POST' ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

Utilizing FORTRAN to store an array and incorporate it into a different program

Is it feasible to generate a large array in one program and then access it in other programs? The array I have in mind is of significant size and creating it from scratch each time the main program runs may be time-consuming. Instead, I am considering crea ...

The page loader failed to load in Chrome due to a timeout, but surprisingly, it loaded

I have added a loader that works perfectly in Chrome, but not in Firefox. In Firefox, the loader keeps loading endlessly without stopping. Here is the HTML code for the loader: <div id="loading"> <img id="loading-image" src="images/ajax-l ...

Utilizing a BUTTON tag does not allow for the implementation of an "extended custom element"

Recently, I delved into the world of web components and experimented with some code: <input is="totally-not-checkbox"> <script> var protoInput = Object.create(HTMLInputElement.prototype); protoInput.createdCallback = function() { ...

React JS is not allowing me to enter any text into the input fields despite my attempts to remove the value props

Currently, I am working on creating a Contact Form using React Js. I have utilized react bootstrap to build the component, but unfortunately, when attempting to type in the input fields, the text does not change at all. import React, {useState} from ' ...

Are there problems with the response values of functions that can handle varying object interfaces?

Currently in the process of developing a command line blackjack app with Node and Typescript, even though I am relatively new to Typescript. My main challenge lies in implementing interfaces for player and dealer objects, as well as creating functions that ...

Next.js optimizes the page loading process by preloading every function on the page as soon as it loads, rather than waiting for them to

My functions are all loading onload three times instead of when they should be called. The most frustrating issue is with an onClick event of a button, where it is supposed to open a new page but instead opens multiple new pages in a loop. This creates a c ...

Issue when transferring req.body attributes to Mongoose Schema

As a beginner in Angular and Node technologies, I must admit my lack of expertise in this area. Encountered an error when attempting to save an Entity from the edit view: 'Cast to ObjectId failed for value "[object Object]" at path "category".' ...

Adjust the window size smoothly to accommodate various height dimensions

Providing Some Background: I am currently developing a Chrome Extension where users have the option to launch it via the default "popup.html", or detach it from the top right corner to use in a separate popup window using window.open. This question also ...

Avoid prompting unsaved changes notification when running OnSelectedIndexChanged event for a drop-down list

Incorporating this jQuery code to detect unsaved modifications and notify users before they navigate away has been really helpful. var _changesMade = false; $(document).ready(function () { $('form').bind($.browser.msie ? 'p ...

Cookie setting issue in Next.js/React: The frustration continues

I'm currently attempting to retrieve a cookie in Next.js using Express, but while the backend functions correctly with Postman and retrieves the cookie token, the frontend is unable to obtain the cookie. Below is my backend code: const express = requi ...

An unexpected 'undefined' occasionally tacked onto 1% of the URLs visitors requested on my website starting from June 12, 2012

Ever since June 12, 2012 at 11:20 TU, I have been noticing strange errors in my varnish/apache logs. At times, after a user has requested a page, I observe a similar request moments later but with the URL string after the last "/" being replaced by "undef ...

Dealing with multiple ajax requests while utilizing a single fail callback

Looking for a solution: I have two arrays containing deferreds. In order to detect failures in the outer or inner 'when' statements, I currently need to use double 'fail' callbacks. Is there a way to consolidate errors from the inner &a ...

Is there a way to add to a dropdown option in select2?

I am in need of creating a dropdown feature that offers users the ability to: 1. Automatically fill in options (based on predetermined values) 2. Add a brand new option if none of the current choices are suitable. I came across select2 as an easy way to i ...