The Hapi response fails to display JSON data in a nested tree format

Hey there! I've got this object with a specific structure. Here it is:

interface FolderWithContent {
    uuid: string
    name: string;
    folders: Array<FolderWithContent>;
    files: Array<Files>;
}

Just a heads up, Files is an extension of Sequelize.Model.

My goal is to return this object using hapi (

return h.response(tree).code(200);
) (tree being my object, obviously)

The issue I'm facing is that even though my object has multiple levels, the response only displays the root and first level. Let me explain with an example:

{
    "name": "folder1.1",
    "uuid": "1",
    "folders": [
        {
            "name": "folder2",
            "uuid": "3986b8ca-314c-4ba8-b47c-9baa29ca7adc"
        },
        {
            "name": "folder2.6",
            "uuid": "7ff93401-1281-419c-9541-fb859c4e79e1",
            "folders": [
                {
                    "name": "folder3.1",
                    "uuid": "8d76aa76-fa42-40c6-9c46-9fa26c6b555c"
                }
            ],
            "files": [
                {
                    "name": "file5",
                    "uuid": "9a8c9aa2-23bd-45e3-bb43-ddf0e085b066"
                }
            ]
        }
    ],
    "files": [
        {
            "name": "file2.2.2",
            "uuid": "88519cec-b19a-4e12-9138-6273ac66ba76"
        },
        {
            "name": "file1",
            "uuid": "9eb5235d-9d04-494d-845c-4a9780bc9687"
        }
    ]
}

In this case, I won't see the folders and files inside folder2.6. I attempted to return tree.folders[2], but it still only displayed the folder name and uuid. Surprisingly, when I returned tree.folders[2].folders, it finally showed me the folders and files within folder2.6.

I also tried calling Json.stringfy(tree), but alas, it encountered the same issue.

Answer №1

After encountering an issue, I delved into finding a solution that worked for me.

It turns out the root cause was related to sequelize. By converting the sequelize models into simple JSON objects, the problem was resolved.

tree.folders = content.folders?.map((folder) => {
        return {
            name: folder.name,
            uuid: folder.uuid,
            updated_at: folder.updated_at,
            synced: folder.synced,
            folders: [],
            files: []
        };
    });
    tree.files = content.files?.map((file) => {
        return {
            name: file.name,
            uuid: file.uuid,
            updated_at: file.updated_at,
            synced: file.synced
        };
    });

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 incorporating the authorization function from next-auth into a TypeScript Next.js 13 app directory

Can you help me understand the proper way to declare the authorize function in [...nextauth].ts? I have been attempting it as shown below: export default NextAuth({ session: { strategy: "jwt" }, providers: ...

Difficulty Launching AlchemyAPI Natural Language Classifier Application on Bluemix

I have managed to deploy the AlchemyAPI Natural Language Classifier Sample App on Bluemix and you can find it here. However, every time I try to run it, I keep receiving the following output: "Not Found Error" This happens regardless of the question I ...

Challenges with JavaScript fetching JSON information

Resolved: To enable AJAX functionality, I needed to upload the files to my server. Currently, I am attempting to retrieve stock information from a JSON file, but no data is being displayed. Upon alerting ajax.status, it returned 0 as the result, indicatin ...

Transforming JSON data into CSV format using Python

I am seeking assistance with extracting statistical data tables from NHL.com and converting them into CSV format for use in Excel later. While I have successfully extracted the tables, I am encountering difficulties when attempting to convert them to CSV. ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...

What is the best way to extract multiple records from an Array?

Below is a simple filter function that filters Rec_pagedItems in an array called allItems. someval(value){ if(value.length>=5){ this._pagedItems= this.allItems.find(e=>e.uniqueid == value || e.name == value ); if(this._pagedItem ...

Creating a spy object in Jasmine for the forEach method of router.events

I have been attempting to create a test case for a component in an application and am having trouble with the constructor. Here is how it looks: constructor(private router: Router, public dialog: MatDialog, private tlsApiServi ...

Navigating through the keys of a parameter that can assume one of three distinct interfaces in TypeScript: a guide

Here is a function example: function myFunc(input: A | B | C) { let key: keyof A | keyof B | keyof C; for(key in input) { let temp = input[key]; console.log(temp); } } The definitions for A, B, and C are as follows: interfa ...

I'm interested in learning how to implement dynamic routes in Nexy.js using TypeScript. How can I

I have a folder structure set up like this: https://i.stack.imgur.com/qhnaP.png [postId].ts import { useRouter } from 'next/router' const Post = () => { const router = useRouter() const { pid } = router.query return <p>Post: {p ...

Guide to serializing and deserializing an ArrayList, including properties of an Object datatype

Is there a way to maintain the object types during the deserialization of a json object? I've noticed that the ArrayList is lost and ends up as an object array, while the rectangle is completely gone. Edit: Unfortunately, I am unable to adjust the ob ...

Steps to display images within a div from a specific directory

Recently, I have encountered a challenge that involves retrieving images from a specific directory, regardless of the number of images present, and then displaying them in a div using an unordered list. I attempted the following code snippet, but unfortuna ...

What is the best way to loop through a JSON object in SQL?

I'm facing a challenge with a JSON variable that contains multiple values presented like this: "["1", "2", "3", "4"]" My goal is to pass this value to an SQL procedure in order to build a query where the WHERE clause includes all the values from the ...

Utilizing the WebSocket readyState to showcase the connection status on the application header

I am currently in the process of developing a chat widget with svelte. I aim to indicate whether the websocket is connected or not by utilizing the websocket.readyState property, which has the following values: 0- Connecting, 1- Open, 2- Closing, 3- Close ...

What is the best way to create a TypeScript type for React props that only allows prop B to be used if prop A is included in the component?

My component Text has 2 props: isHideable: boolean and hidden: boolean. How can I only allow Hidden as a prop when isHideable is set to true? Currently, both isHideable and hidden are being accepted which is not the desired behavior: type Props = { chi ...

The JObject parser abruptly halts its execution without producing any results or indicating any errors

I have been attempting to retrieve and parse a JSON response from a webapi using the following code: var pemail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44302b2a3d37042329252d286a272b29">[email protected]</ ...

This code cannot be called as a function, Every individual in the union

My approach has been aligned with the current architecture, focusing on reducing complexity as much as possible. I have strived for the best possible outcome, but encountered a single failed test along the way. After three days of struggling, I'm cl ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

Guide on converting an entire request String into Json format on Android

My task is to send the following Json: {"method":"startSession", "params":["email" "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70151d11191c30151d11 2291e71">[email protected]</a>", "password" "1234", "stayLog ...

A step-by-step guide on converting JSON data from JavaScript to C# variables

Hey there! I have a JavaScript snippet where I am sending an array to my C# file in JSON format. var r=['maths','computer','physics'] $.post("Global.aspx", { opt: "postpost", post: w.val(),tags:JSON.stringify(r) }, function ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...