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

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 };
    });
  });
};

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:

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

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

`Integrate Passport Azure AD authentication into your GraphQL Server's Context`

Seeking assistance from experienced individuals to tackle some async JavaScript issues. I am trying to secure a GraphQL server using the Passport library and the passport-azure-ad strategy. The validation of incoming Access Tokens seems to be working fine ...

Removing nested divs using JavaScript

My website has a nested div structure which contains multiple child divs. Here is an example of the div structure: <div id="outside-one"> <div class="inside" id="1"></div> <div class="inside" id="2"></div> <div ...

"Disappearing Act: The Mysterious Vanishing of the JS

When I run my project using a node server, I have to execute three commands in the command prompt every time: npm install node server grunt serve I included a pagination directive from Git-hub in my project. However, every time I initialize the project ...

Enhance your website with jQuery's animate() feature for dynamic

My current implementation of jQuery's animate function looks like this: var css1 = { display: "block", marginTop: 20 }; var direction = "marginTop"; $(element).animate(css1, 150, 'swing'); I've noticed the marginTop ...

Using JSON as HTML data within Flexbox for interactive hyperlink rollovers

Utilizing JSON to extract HTML data with unique html tags within Flex has presented a challenge. The limited support for HTML in Flex has made it difficult to implement a basic font color rollover effect on links. While Flex only allows for a few HTML tags ...

What is the name of the event triggered when a jQuery UI draggable element is reverting back to its original position?

I am currently using jQuery UI to create a draggable element on my website. I have added a function to the drag event that continuously tracks the position of the element while the user is dragging it. Additionally, I have set revert: true on this element ...

What is the best way to access a value within a JSON object in a React render method?

Overview I am currently working on creating a blog using React and JSON data. Upon checking this.state.blogs, I am getting the output of: [object Object],[object Object],[object Object]. I have attempted to use the .map function but I am not sure how to ...

Updating a particular attribute within a JSON object in a JSON Array using MySQL

Currently, my MySQL database includes a table with a JSON column that stores data as shown below: [{"id": 1, "value": 23.4}, {"id": 2, "value": 54.3}, {"id": 3, "value": 4.33}] I am looking to update the value property of all objects in this colum ...

Create a sleek transition for your Bootstrap 4 fixed Navbar by having it smoothly slide down and change to a

Throughout my experience with HTML/CSS, I have predominantly relied on themes that included this feature by default. However, as I now venture into building from scratch, I find myself struggling to recreate it. You'll notice that I have a stylish fi ...

The implementation of pushing inside a foreach loop is not correctly adding elements to

I have encountered an issue with running a foreach loop and adding values to an array in my code. The first foreach loop works as expected, adding values properly to the array. However, the second foreach loop seems to be malfunctioning as none of its valu ...

tips for looping through a python json response object

I'm having trouble displaying stock market news data retrieved from an API call within the last 7 days. When I run the program, it doesn't show anything. How can I iterate through all the values and print the date, text, sentiment, and tickers wi ...

Top method for verifying email existence in ASP.NET database

In our current asp.net web application, we are facing some challenges with using the update panel on the user registration page to check for existing users. These issues include: 1- The update panel tends to slow down the process. 2- The focus is lost wh ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

How to retrieve an anchor element from a list using JavaScript

My current code loops through each <li> within a <td> cell and adds a class to the <li>. I have now inserted <a> tags between each <li> and am facing challenges in accessing the <a> tags. What I actually want is to assig ...

Exploring each item within oData: A guide

After writing the code statement above, I am able to see the attached image. Now, my challenge is accessing the "label" property inside each object. How can I iterate through these objects and retrieve their "label" properties? item.getModel().oData; I a ...

Ways to ensure the axios call is completed before proceeding with the codeexecution

I need to use axios to send a request and retrieve some data that I want to pass as a prop to a React Component. Here's my render function: render() { boards = this.fetchBoardList(); return ( <div className="app-wrapper"> ...

Storing JSON data in a MongoDb database using the Sails.js framework

I'm looking to build my database using an external API. To begin, I've created a function called loadData(req, res){} in my DBController that retrieves data from the API in JSON format. Now, I want to save this imported JSON data into my mongoDB ...

An issue occurred while parsing a JSON file, throwing a JSON decoder error with the message: "

Currently, I am in the process of developing a code to upload a model called train_and_upload_demo_model.py into Solr by using the settings present in the "config.json" file. However, I have encountered an error that states the following: json.decoder.JSON ...

Tips for modifying `sourceMappingURL` in parcel js

Is there a way to manually adjust the path of //# sourceMappingURL in the generated bundle.js? The current configuration in Parcel is causing the path to be incorrect for bundle.js.map. Parcel setup: "scripts": { "watch:js": &quo ...