Retrieve items from an array using a series of nested map operations

When I execute the query below, it transforms the json data into objects - 1st level being a map (This works fine as expected)

const customerOptions = () => {
  return customersQuery.edges.map(({ node: { id, name } }) => {
    return { key: id, text: name, value: id };
  });
};

Output https://i.sstatic.net/GcRLg.png

However, when I loop through my json data using nested map, I get an array of objects instead of the format I anticipated from the first query.

const departmentOptions = () => {
  return customersQuery.edges.map(({ node: { departments } }) => {
    return departments.map(({ id, name }) => {
      return { key: id, text: name, value: id };
    });
  });
};

https://i.sstatic.net/THibt.png

My objective is to have the second level array mapping stored as a list of objects, resulting in a total of 40 objects.

This is a sample JSON structure used:

{
  "data": {
    "customersQuery": {
      "edges": [
        {
          "node": {
            "id": 20,
            "name": "Customer name 20",
            "departments": [
              {
                "id": 39,
                "name": "Department name 20"
              },
              {
                "id": 40,
                "name": "Department name 20"
              }
            ]
          }
        },
        // Additional entries for other customers and departments....
      ]
    }
  }
}

For reference, here is how my GraphQL query appears: https://i.sstatic.net/cY1mK.png

Answer №1

To optimize the code, consider using a reduce() instead of a map() for the outer function call and either concat() or push.apply() for the inner map() in the reducer function:

With concat():

let customersQuery = {"edges":[{"node":{"id":20,"name":"Customer name 20","departments":[{"id":39,"name":"Department name 20"},{"id":40,"name":"Department name 20"}]}},{"node":{"id":19,"name":"Customer name 19","departments":[{"id":37,"name":"Department name 19"},{"id":38,"name":"Department name 19"}]}},{"node":{"id":18,"name":"Customer name 18","departments":[{"id":35,"name":"Department name 18"},{"id":36,"name":"Department name 18"}]}},{"node":{"id":17,"name":"Customer name 17","departments":[{"id":33,"name":"Department name 17"},{"id":34,"name":"Department name 17"}]}},{"node":{"id":16,"name":"Customer name 16","departments":[{"id":31,"name":"Department name 16"},{"id":32,"name":"Department name 16"}]}},{"node":{"id":15,"name":"Customer name 15","departments":[{"id":29,"name":"Department name 15"},{"id":30,"name":"Department name 15"}]}},{"node":{"id":14,"name":"Customer name 14","departments":[{"id":27,"name":"Department name 14"},{"id":28,"name":"Department name 14"}]}},{"node":{"id":13,"name":"Customer name 13","departments":[{"id":25,"name":"Department name 13"},{"id":26,"name":"Department name 13"}]}},{"node":{"id":12,"name":"Customer name 12","departments":[{"id":23,"name":"Department name 12"},{"id":24,"name":"Department name 12"}]}},{"node":{"id":11,"name":"Customer name 11","departments":[{"id":21,"name":"Department name 11"},{"id":22,"name":"Department name 11"}]}},{"node":{"id":10,"name":"Customer name 10","departments":[{"id":13,"name":"Department name 10"},{"id":14,"name":"Department name 10"}]}},{"node":{"id":9,"name":"Customer name 9","departments":[{"id":11,"name":"Department name 9"},{"id":12,"name":"Department name 9"}]}},{"node":{"id":8,"name":"Customer name 8","departments":[{"id":19,"name":"Department name 8"},{"id":20,"name":"Department name 8"}]}},{"node":{"id":7,"name":"Customer name 7","departments":[{"id":15,"name":"Department name 7"},{"id":16,"name":"Department name 7"}]}},{"node":{"id":6,"name":"Customer name 6","departments":[{"id":17,"name":"Department name 6"},{"id":18,"name":"Department name 6"}]}},{"node":{"id":5,"name":"Customer name 5","departments":[{"id":9,"name":"Department name 5"},{"id":10,"name":"Department name 5"}]}},{"node":{"id":4,"name":"Customer name 4","departments":[{"id":7,"name":"Department name 4"},{"id":8,"name":"Department name 4"}]}},{"node":{"id":3,"name":"Customer name 3","departments":[{"id":5,"name":"Department name 3"},{"id":6,"name":"Department name 3"}]}},{"node":{"id":2,"name":"Customer name 2","departments":[{"id":3,"name":"Department name 2"},{"id":4,"name":"Department name 2"}]}},{"node":{"id":1,"name":"Customer name 1","departments":[{"id":1,"name":"Department name 1"},{"id":2,"name":"Department name 1"}]}}]};

With push.apply():

let customersQuery = {"edges":[{"node":{"id":20,"name":"Customer name 20","departments":[{"id":39,"name":"Department name 20"},{"id":40,"name":"Department name 20"}]}},{"node":{"id":19,"name":"Customer name 19","departments":[{"id":37,"name":"Department name 19"},{"id":38,"name":"Department name 19"}]}},{"node":{"id":18,"name":"Customer name 18","departments":[{"id":35,"name":"Department name 18"},{"id":36,"name":"Department name 18"}]}},{"node":{"id":17,"name":"Customer name 17","departments":[{"id":33,"name":"Department name 17"},{"id":34,"name":"Department name 17"}]}},{"node":{"id":16,"name":"Customer name 16","departments":[{"id":31,"name":"Department name 16"},{"id":32,"name":"Department name 16"}]}},{"node":{"id":15,"name":"Customer name 15","departments":[{"id":29,"name":"Department name 15"},{"id":30,"name":"Department name 15"}]}},{"node":{"id":14,"name":"Customer name 14","departments":[{"id":27,"name":"Department name 14"},{"id":28,"name":"Department name 14"}]}},{"node":{"id":13,"name":"Customer name 13","departments":[{"id":25,"name":"Department name 13"},{"id":26,"name":"Department name 13"}]}},{"node":{"id":12,"name":"Customer name 12","departments":[{"id":23,"name":"Department name 12"},{"id":24,"name":"Department name 12"}]}},{"node":{"id":11,"name":"Customer name 11","departments":[{"id":21,"name":"Department name 11"},{"id":22,"name":"Department name 11"}]}},{"node":{"id":10,"name":"Customer name 10","departments":[{"id":13,"name":"Department name 10"},{"id":14,"name":"Department name 10"}]}},{"node":{"id":9,"name":"Customer name 9","departments":[{"id":11,"name":"Department name 9"},{"id":12,"name":"Department name 9"}]}},{"node":{"id":8,"name":"Customer name 8","departments":[{"id":19,"name":"Department name 8"},{"id":20,"name":"Department name 8"}]}},{"node":{"id":7,"name":"Customer name 7","departments":[{"id":15,"name":"Department name 7"},{"id":16,"name":"Department name 7"}]}},{"node":{"id":6,"name":"Customer name 6","departments":[{"id":17,"name":"Department name 6"},{"id":18,"name":"Department name 6"}]}},{"node":{"id":5,"name":"Customer name 5","departments":[{"id":9,"name":"Department name 5"},{"id":10,"name":"Department name 5"}]}},{"node":{"id":4,"name":"Customer name 4","departments":[{"id":7,"name":"Department name 4"},{"id":8,"name":"Department name 4"}]}},{"node":{"id":3,"name":"Customer name 3","departments":[{"id":5,"name":"Department name 3"},{"id":6,"name":"Department name 3"}]}},{"node":{"id":2,"name":"Customer name 2","departments":[{"id":3,"name":"Department name 2"},{"id":4,"name":"Department name 2"}]}},{"node":{"id":1,"name":"Customer name 1","departments":[{"id":1,"name":"Department name 1"},{"id":2,"name":"Department name 1"}]}}]};

When dealing with large inner arrays, using concat() is preferable as it utilizes heap memory but entails copying data from the existing array into a new one each time.

For relatively small inner arrays, push.apply() is more efficient since it makes use of stack memory, adds data to the end of the current array without explicit copying, and suits smaller datasets better.

Answer №2

map operates on the item level and does not change the length of the array. To flatten the resulting array, you can use methods like concat

const departmentOptions = () => {
  return [].concat.apply([], customersQuery.edges.map(({ node: { departments } }) => {
    return departments.map(({ id, name }) => {
      return { key: id, text: name, value: id };
    });
  }));
};

Another approach is to use spread syntax

const departmentOptions = () => {
  return [].concat(...customersQuery.edges.map(({ node: { departments } }) => {
    return departments.map(({ id, name }) => {
      return { key: id, text: name, value: id };
    });
  }));
};

Answer №3

To gather data from each department, utilize the reduce and forEach functions to populate an array.

const customersQuery = {"edges":[{"node":{"id":20,"name":"Customer name 20","departments":[{"id":39,"name":"Department name 20"},{"id":40,"name":"Department name 20"}]}},{"node":{"id":19,"name":"Customer name 19","departments":[{"id":37,"name":"Department name 19"},{"id":38,"name":"Department name 19"}]}},{"node":{"id":18,"name":"Customer name 18","departments":[{"id":35,"name":"Department name 18"},{"id":36,"name":"Department name 18"}]}},{"node":{"id":17,"name":"Customer name 17","departments":[{"id":33,"name":"Department name 17"},{"id":34,"name":"Department name 17"}]}},{"node":{"id":16,"name":"Customer name 16","departments":[{"id":31,"name":"Department name 16"},{"id":32,"name":"Department name 16"}]}},{"node":{"id":15,"name":"Customer name 15","departments":[{"id":29,"name":"Department name 15"},{"id":30,"name":"Department name 15"}]}},{"node":{"id":14,"name":"Customer name 14","departments":[{"id":27,"name":"Department name 14"},{"id":28,"name":"Department name 14"}]}},{"node":{"id":13,"name":"Customer name 13","departments":[{"id":25,"name":"Department name 13"},{"id":26,"name":"Department name 13"}]}},{"node":{"id":12,"name":"Customer name 12","departments":[{"id":23,"name":"Department name 12"},{"id":24,"name":"Department name 12"}]}},{"node":{"id":11,"name":"Customer name 11","departments":[{"id":21,"name":"Department name 11"},{"id":22,"name":"Department name 11"}]}},{"node":{"id":10,"name":"Customer name 10","departments":[{"id":13,"name":"Department name 10"},{"id":14,"name":"Department name 10"}]}},{"node":{"id":9,"name":"Customer name 9","departments":[{"id":11,"name":"Department name 9"},{"id":12,"name":"Department name 9"}]}},{"node":{"id":8,"name":"Customer name 8","departments":[{"id":19,"name":"Department name 8"},{"id":20,"name":"Department name 8"}]}},{"node":{"id":7,"name":"Customer name 7","departments":[{"id":15,"name":"Department name 7"},{"id":16,"name":"Department name 7"}]}},{"node":{"id":6,"name":"Customer name 6","departments":[{"id":17,"name":"Department name 6"},{"id":18,"name":"Department name 6"}]}},{"node":{"id":5,"name":"Customer name 5","departments":[{"id":9,"name":"Department name 5"},{"id":10,"name":"Department name 5"}]}},{"node":{"id":4,"name":"Customer name 4","departments":[{"id":7,"name":"Department name 4"},{"id":8,"name":"Department name 4"}]}},{"node":{"id":3,"name":"Customer name 3","departments":[{"id":5,"name":"Department name 3"},{"id":6,"name":"Department name 3"}]}},{"node":{"id":2,"name":"Customer name 2","departments":[{"id":3,"name":"Department name 2"},{"id":4,"name":"Department name 2"}]}},{"node":{"id":1,"name":"Customer name 1","departments":[{"id":1,"name":"Department name 1"},{"id":2,"name":"Department name 1"}]}}]};
 
const departmentOptions = () => {
  return customersQuery.edges.reduce((acc, { node: { departments } }) => {
    departments.forEach(({ id, name }) => {
      acc.push({ key: id, text: name, value: id });
    });
    
    return acc;
  }, []);
};

console.log(departmentOptions());

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

Guide on developing a personalized validation system with Vuetify regulations for verifying the presence of an item

I'm currently working on my first CRUD web app using Vue 2 + Vuetify, but I've hit a roadblock while trying to add validation to a form. Specifically, I need to ensure that no item with the same title already exists in the database. You can view ...

Tips for accessing an Angular service from different Angular controllers

I am a beginner with angular js and I am currently exploring ways to call the service provided in the code snippet below from a controller. The service is defined as follows. app.factory('myappFactory', ['$http', function($http) { v ...

Is it possible to replicate a stale closure similar to React's useEffect hook without the use of the useEffect hook?

I have a good understanding of closures, but I am struggling to grasp how a stale closure can be created in React's useEffect without providing an exhaustive dependencies array. In order to explore this concept further, I am attempting to replicate a ...

Rest API question: Based on the output provided, how should the URL format be correctly written?

If I were in charge of developing a rest api that generated the following result from the given URL: /owner/123/animal {     {       Owner: 123,       Animal: Cat     },     {       Owner: 123,       Animal: Dog     },     {   ...

Passing values from a Laravel controller to a Vue component as a prop

At the moment, I have a Laravel route that directs to the index function of my controller with an ID passed, where I then return the ID in a view. public function index($id) { return view('progress') ->with('identifier', ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Looking for reliable resources on establishing a connection between a Google account and my application

I am currently working on creating a react native app that aims to simplify the user login process by allowing them to link their Google account with just one click. This way, users won't have to constantly log in every time they use the app. While I ...

I am seeking guidance on retrieving the value of a text box that is activated by a radio button through jquery within the provided code

When conducting my test case, the user is presented with a choice between ielts and toefl. If the user chooses ielts, an input box appears where they can enter their ielts score. My goal is to extract and store the value entered in that input box. Check ou ...

Develop a specialized WordPress widget featuring several unique text areas for enhanced customization

class ad_widget extends WP_Widget { function __construct() { $widget_ops = array( 'classname' => 'ad-widget-container', 'description' => __( ' Ad WIDGET' ) ); parent::__construct( 'ad-widget', ...

Creating a form for adding and editing using React Hook Form

I'm currently working on creating a form that can handle both the creation and editing of a product by passing values through an object. The form functions perfectly for creating a product, but I'm facing challenges in making it work for editing ...

Show JSON information from a jQuery post request

Greetings, I am currently working on implementing a login script using Ajax. My objective is to retrieve and display data such as email and username, and then store it in local storage. Although I can successfully obtain the data in JSON format, I want to ...

Creating a .env file using Vanilla JavaScript to securely store and conceal tokens

I am currently working on a vanilla JavaScript project. Within the app.js file, I am making an API call to retrieve specific values. Initially, I tested the API using Postman by including all the necessary headers there and then implemented the code in my ...

Loop through the JSON data to obtain distinct values for certain indices

My PHP script retrieves data with the following query: SELECT objective,signal_type,signal_name FROM signals WHERE channel="Email" This is how the data is returned: [ { "objective": "Awareness", "signal_type": "Efficiency", " ...

The process of summing a 2D array can be time-consuming

In my Android app development using RenderScript, I am aiming to create a 2D array that calculates the sum of all integers within a rectangle starting from the origin up to (x,y). As specified here, RenderScript is based on C99. Any function with the RS_K ...

Is it possible for me to develop a mobile application using JavaScript, HTML, and CSS and distribute it for sale on the App Store, Google Play Store, and Microsoft Mobile App Store at

I have a keen interest in web standards such as Javascript, HTML, and CSS. My goal is to utilize these languages to develop applications for mobile devices like phones and tablets. I am also considering selling these applications on various platforms inclu ...

Utilize Next JS pages api to generate dynamic routes based on unique ids

In the content of my website, there is a collection of objects named stories that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail. I intend to enable users to click on any story link within the ...

React-scripts testing now displays error messages without a traceback

After recreating the browser version of the TacticToy game using React, I encountered an issue while writing unit tests. The problem is that there is no complete traceback provided for a custom exception, with only the test function being highlighted: htt ...

What is the method for generating a random array value in C++?

Hey there, I'm feeling a bit stuck and could use some assistance. I need to store values in an array with 20 slots using a specific algorithm. However, when I try to input the 9th value into the array, I end up with a huge number that doesn't see ...

What is the process for setting up a vertical carousel in Bootstrap 5 with a stationary previous image?

Looking for assistance with my vertical carousel project. Is there a way to create a vertical carousel in bootstrap 5 with the previous image fixed? I found a slider on this website: zara.com/jp/en/ I want to maintain the previous image in a fixed posit ...