What is the best way to showcase the data within an array { data: { results: [ [Object] ], total: 1, page: 1 }, error: null } when responding?

Here's a code snippet I am working with:


let result = null;
    await fetch(request)
      .then((response) => {
        if (response.status === 201) {
          console.log("Success");
          result = response.json();
        } else {
          throw new Error("Something went wrong on API server!");
        }
      })
      .catch((error) => {
        console.error(error);
      });
    console.log("Response:", await result);
  });
});

The received output is as follows:

[0-0] Success [0-0] Response: { data: { results: [ [Object] ], total: 1, page: 1 }, error: null }

However, when checking the response in Postman, it appears like this:

{
    "data": {
        "results": [
            {
                "customerId": 123,
                "firstName": "Name",
                "lastName": "LastName",
                "displayName": "Name LastName",
                "phoneNumber": "4159436367",
                "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c39313d35301c39313d3530723f3331">[email protected]</a>",
                "notes": null,
                "memberNumber": null,
                "highlights": null
            }
        ],
        "total": 1,
        "page": 1
    },
    "error": null
}

How can I format the array response to be displayed similar to how it appears in Postman? Thank you for any assistance.

I attempted to modify the code with this addition:

const parsedResponce = result;
const obj = JSON.parse(parsedResponce);
console.log(obj.phoneNumber);

This led to the following error:

SyntaxError: Unexpected token o in JSON at position 1

Answer №1

To display a nicely formatted object, you can utilize the JSON.stringify method.

let data = {
    "info": {
        "details": [
            {
                "userId": 456,
                "username": "User",
                "lastName": "Lastname",
                "displayName": "User Lastname",
                "phoneNumber": "4159436367",
                "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36535b575f5a76535b575f5a1855595b">[email protected]</a>",
                "notes": null,
                "memberId": null,
                "highlights": null
            }
        ],
        "totalResults": 1,
        "currentPage": 1
    },
    "errorMessage": null
};
console.log(JSON.stringify(data, null, 4));

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

Arrange rows in ascending order using jQuery

This script is functioning correctly but only examines the first column. I would like to alter it to check the second column for points instead. How can I make this adjustment? HTML Table: <table width="100%"> <thead> <tr> ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

Placing a three-dimensional object in the corners of the canvas using three.js

I'm trying to position a 3D object in either corner of my canvas automatically, regardless of its size. https://i.sstatic.net/IWgr1.png After finding a solution on stackoverflow: I implemented the following code for my object: mesh.position.set(-( ...

Using MeanJS to assign a Mongoose object reference to an array in Angular

Having an issue with MeanJS and using the $update function of the $resource service in Angular provided by MeanJS. Here is a basic outline of my problem: Mongoose schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Lotion ...

What is the process for retrieving values from a nested JSONObject within the entity response output-type of an API using KOTLIN?

My goal was to extract an array of JSONObjects from the variable "result" within the ResponseEntity< JSONObject >. <200 OK,{"response":"success","count":0,"maintenanceDetails":[{"date":"2020& ...

To retrieve the request parameter within the socket.on operation

As a newcomer to node.js, I may have made some mistakes along the way. Please bear with me. When trying to retrieve parameters passed in the URL like localhost:3000?id=man&fm=gilli, I used the following code: app.get('/',function(req, re ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Can you tell me how to achieve the functionality of the ".get" statement in JavaScript that is present in python-firebase?

After writing Python code that retrieves the entire JSON database, I attempted to achieve the same functionality in JavaScript without success. Despite its apparent straightforwardness, I have yet to discover a viable solution. var firebase = require(&apo ...

Author Names Missing from Book List in Locallibrary Tutorial

After spending several years working on front-end development, I've decided to delve into back-end development to expand my skill set. Following the Basic Node and Express course from FreeCodeCamp Curriculum, I am now following the MDN Express Localli ...

Can data be presented in AngularJS without the use of scope variables?

I have a method: <span ng-init="getJobApplicantsList(jobId)">(number should be display here)</span> Is there a way to display the data without having to store it in a scope variable? I need to use this method in many places. This is my cont ...

How to retrieve document.getElementsByName from a separate webpage using PHP and javascript

Hey there, I've been searching for a solution to this issue but haven't had any luck so far. I'm attempting to retrieve the value of the name test from an external website. <input type="hidden" name="test" value="ThisIsAValue" /> Up ...

I am facing an issue with my JavaScript variable that keeps changing temporarily. How can I ensure that its value remains permanent? Console log

I recently made some edits to the p tags, but only one of them appeared to have changed. Upon trying to display the changes again, I couldn't see any difference. Here's the code snippet that I'm working with: $(document).ready(function() ...

Send the content of an HTML file to a JavaScript variable

I'm working on using a template.html file as an email template in loopback/nodejs. In PHP, I know how to include the template.php file and store it in a variable like this: ob_start(); include template.php; $template = ob_get_clean(); Is there a way ...

display elements in indexed alphabetical order

Is it possible to format the $index output in alphabetical order instead of numerical? <div ng-repeat="name in names">{{$index}}</div> I am wondering if this can be achieved. ...

Obtain details regarding a worker's collision

This code snippet is being used to manage cluster crashes within a node application cluster.on('exit', function (worker, code, signal) { console.log("error in cluster",worker); console.log("cluster code",code); console.l ...

InnerHTML syntax for creating the button in the cell is not functioning properly with the HTML onclick event

I'm facing an issue with my code where I am trying to insert a button into a table cell. The button has an action assigned to it using the onclick attribute. However, no matter how I try to use single quotes with or without backslashes in the syntax o ...

Duplicate the appearance of a webpage exactly as it is displayed, without regard to the underlying source code

Looking to transfer content from a webpage to a Word document? Specifically, an installation guide, with additional comments about our own installation process. Seems easy enough - just copy and paste, right? Not quite. The issue lies in the structure of ...

Verify whether the div contains a specific class before triggering the animation

I'm attempting to create an animation following a user interaction with the Owl Carousel drag feature. The issue I'm encountering is that the code referencing $(this) does not recognize the .nav-item element with the .active class. Any insights ...

What is the most effective method for organizing an object by its values using multiple keys?

I'm interested in utilizing the sort method mentioned in the link but I am facing { "CYLINDER": 2986, "HYDRAULIC": 1421, "JACKS": 84, "INSTALLATION": 119, "REAR": 61, "JACK": 334, "TUBE": 1, "FEED": 114, "ASSEMBLY": 326, "DCS": 2 ...

Attempt to prevent the loading of images using javascript

Is it possible to pause the downloading of images using JavaScript? I am seeking a way to extract all URLs from image tags and only initiate the image loading process when a user scrolls to a specific image. I am aware that the download can be halted using ...