Molding information for a problem solver

Imagine a scenario where a resolver retrieves quotes from various books stored in a mongo db. This is how the data is structured within the database!

    getQuotes: async () => {
      const getQuotes = await booksModel.find({}, "quotes");
      console.log(getQuotes);
      // #1

      for (const element of getQuotes) {
        const test = element.quotes;
        console.log(test)
        // #2

        Object.values(test).forEach((val) => {
          console.log(val);
          // #3
          
          return val;
        });
      }
    },

The result closely resembles the expected data structure...

This is console.log #3!

{
  book: 1,
  page: 12,
  excerpt: 'asaaaad',
  comment: 'asd',
  _id: 'N_YOT_Gms_fvAqQKL3Y23'
}
{
  book: 1,
  page: 12,
  excerpt: 'sdfsdfsdfsdf',
  comment: 'asd',
  _id: 'QP5iLh3Gj2X8ZcSN7hoPF'
}
{
  book: 2,
  page: 12,
  excerpt: 'asaasdasdaad',
  comment: 'asd',
  _id: '2kdkfgW6MERwGtvbXph9e'
}

This is console.log #2!

[
  {
    book: 1,
    page: 12,
    excerpt: 'asaaaad',
    comment: 'asd',
    _id: 'N_YOT_Gms_fvAqQKL3Y23'
  },
  {
    book: 1,
    page: 12,
    excerpt: 'sdfsdfsdfsdf',
    comment: 'asd',
    _id: 'QP5iLh3Gj2X8ZcSN7hoPF'
  }
]
[
  {
    book: 2,
    page: 12,
    excerpt: 'asaasdasdaad',
    comment: 'asd',
    _id: '2kdkfgW6MERwGtvbXph9e'
  }
]

This is console.log #1!

[
  { _id: 'leO68YLuG_mG4KS491Kpz', quotes: [ [Object], [Object] ] },
  { _id: 'ymbUWql0sREAKuaVXZ_KY', quotes: [ [Object] ] }
]

I seem to be struggling with organizing the data into a neat array using forEach in my graphql resolver. Any suggestions on approaching this differently? It's been quite some time since I delved into this, so pardon any missteps; I gave it my best shot :p

Answer №1

Using the .flatMap method can simplify your code:

getItems: async () => {
    const items = await inventoryModel.find({}, "items");
    return items.flatMap((item) => item.items);
}

const items = [{
    _id: 'leO68YLuG_mG4KS491Kpz',
    items: [{
        category: 1,
        name: 'apple',
        quantity: 10,
        _id: 'N_YOT_Gms_fvAqQKL3Y23'
      }, {
        category: 1,
        name: 'banana',
        quantity: 20,
        _id: 'QP5iLh3Gj2X8ZcSN7hoPF'
      
    }],
  }, {
    _id: 'ymbUWql0sREAKuaVXZ_KY',
    items: [{
        category: 2,
        name: 'orange',
        quantity: 15,
        _id: '2kdkfgW6MERwGtvbXph9e'
    }]
}];

console.log(items.flatMap((item) => item.items));

If your environment doesn't support it, you can add the following polyfill:

if (!Array.prototype.flatMap) {
  Object.defineProperty(Array.prototype, 'flatMap', {
    configurable: true,
    writable: true,
    value: function () {
      return Array.prototype.map.apply(this, arguments).flat(1);
    },
  });
}

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

Attempting to execute the command npm run dev, but receiving the error message "No entries found."

Whenever I try to run "npm run dev", I encounter the following error: Server running at http://localhost:1234 ...

The state may be modified, but the component remains unchanged

I've been tasked with implementing a feature on a specific website. The website has a function for asynchronously retrieving data (tickets), and I need to add a sorting option. The sorting process occurs on the server side, and when a user clicks a s ...

While experimenting with p5.js, I encountered an issue where I received the error message stating that "loadAnimation is not defined and createSprite not defined." This problem persists even when using VSCode

let background, sleeping, brushing, gyming, eating, drinking, moving, astronaut; function preload() { background = loadImage("images/iss.png"); sleeping = loadAnimation("images/sleep.png"); brushing = loadAnimation("images/ ...

What is the file path on a Windows local disk where Flutter Android emulator stores files using path_provider?

I've been searching high and low for an answer to this question with no luck. One would think that finding the location of the json file should be one of the basics covered when discussing the path_provider package. Despite printing the debug console ...

Utilizing external functions in Node.js by importing them from different files

Struggling to import methods from my ./db/index.js into my server.js file in order to retrieve data from the database and show it. The content of /db/index.js is as follows: 'use strict'; const pgp = require('pg-promise')(); const pg ...

Changing the array of objects: various operations on arrays and objects

Array of Data [ {group: 'a', tab: "1", name: 'input1'}, {group: 'b', tab: "1", name: 'input2'}, {group: 'b', tab: "1", name: 'input3'}, {group: 'c', tab: "2", name: 'input4&apo ...

A collection of varying length arrays

#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char *names = NULL; int capacity = 0; int size = 0; printf("Please enter 'end' to stop adding names\n"); while (1) { ...

Issue with navbar overlay: when screen width is minimized, components do not remain in one row

I'm encountering an issue with my navigation bar. I need it to maintain its size when the page is minimized, but currently, the navbar elements stack on top of each other as I reduce the browser window width. Before reducing browser window width: htt ...

Unfulfilled expectation of a promise within an array slipping through the cracks of a for loop

I have a function that generates a Promise. Afterward, I have another function that constructs an array of these promises for future utilization. It is important to note that I do not want to execute the promises within the array building function since so ...

AttributeError: The class 'Rules' does not contain the attribute '__temperature'

My project involves a program that receives inputs from sensors and processes them based on pre-defined rules stored within a class. However, I am encountering issues with passing sensor variables into the rules class. The error message 'Rules object ...

Saving an array of Int64 variables with NSCoding in Swift: A step-by-step guide

Currently, I'm using NSCoding to save an array of Int variables in the following manner: var myArray = [Int]() myArray = aDecoder.decodeObjectForKey("MyArray") as! [(Int)] aCoder.encodeObject(myArray, forKey: "MyArray") Now, I need to save an arra ...

A comparison between RXJS5 and Promise.all

Is there a Promise.all equivalent in this situation? let promise1 = performTaskA(); // some promise let promise2 = performTaskB(); // another promise // wait for both promises to complete. Promise.all([promise1, promise2], data => { // do somethin ...

Using express to activate http compression

Currently experimenting with the Darksky API and came across a query parameter that caught my attention: The extend=hourly option is available. With this option, hour-by-hour data for the next 168 hours will be returned rather than just the next 48. It i ...

Disable the second tab within an Angular md-tabs component

Are there any attributes in angular material md-tabs that can be used to disable a tab, similar to what is available in Bootstrap? $scope.tabs = [{ title: 'Dynamic Title 1', content: 'Dynamic content 1' }, { title: 'Dy ...

Changing the data type of a column in an Excel file from XLSX to

I am currently working with the XLSX npm package and attempting to download a sample Excel file, add some data to it, and then upload it back. The fields in the file include MOBILE NUMBER, DATE, TIME, and NAME. When I upload the file, the values for the DA ...

Restrict Text Input Field to Accept Only Specific Domain

Hey there! I've set up a text input box for users to link their Tripadvisor page to their profile. I want to make sure that when they paste the URL in, it is checked for the correct format. For example, if someone pastes: or , then allow the link. Ho ...

Steps for displaying the elements of a JavaScript object

Hello, I am currently diving into the world of JavaScript and have managed to successfully print an object to the console with the code snippet below: clickEvents: { click:function(target) { console.log(target); } } Upon viewing the conso ...

Sorry, but we couldn't complete your request: User verification unsuccessful: email must be provided

Every time I attempt to save a user's credentials to the mongo database, an error pops up saying: "User validation failed: email: Path email is required." I am clueless as to why this issue keeps happening. It only started occurring when I added the v ...

Is it possible for lazy loaded features in Angular 6 to share state between features using ngrx?

Suppose I have a mobile application that utilizes lazy loading and also implements ngrx to manage state. In this setup, each feature has its own state instance with respective reducers, actions, etc. For instance: product-feature product-edit prod ...

Guide to converting an arraylist of custom objects into JSON using JavaScript

I have a List returned to the jag. It is of type (java.util.List) and I need to print it as a json. var storeForum = Packages.org.wso2.carbon.forum.registry.RegistryForumManager; var forum = new storeForum(); var start = request.getParameter(&a ...