Deleting a string by utilizing the Ternary operator in JavaScript

How do I remove the [object Object] from my output shown in the console?

I'm looking to print the output without the [Object Object]. Is it possible to achieve this using a ternary operation?

data:[object Object]
  text:Data is supplied by Government
  link:https://en.wikipedia.org/

This is the code snippet:

const GetData = (obj, step) => {

    let padSpace = ""

    for (let j=0; j < step; j++) {
      padSpace += ''
    }

    for (let k in obj) {
      console.log(padSpace + k + ':' + obj[k])
      if (typeof(obj[k]) === "object") {
        if (Array.isArray(obj[k])) {
          obj[k].forEach(element => {
              if (typeof(element === "object")) {
                GetData(element, step + 1);
              } else {
                console.log(padSpace + element)
              }
            }
          );
        } else {
          GetData(obj[k], step + 1);
        }
      } else {}
    }

I would like the output to be:

Answer №1

This specific test will always result in a pass because when checking the typeof true and false, both return "boolean" which is considered truthy.

if (typeof(element === "object")) {

Experiment with:

if (typeof element === "object") {

The reference to a ternary operation seems unrelated and unnecessary here.


To prevent displaying [object Object] , you can reposition the current console.log statement and introduce an additional one like this:

for (let prop in entity) {  
  if (typeof entity[prop] === "object") {
    console.log(padString + prop + ':');
    if (Array.isArray(entity[prop])) {
      entity[prop].forEach(element => {
        if (typeof element === "object") {
          formatData(element, level + 1);
        } else {
          console.log(padString + element)
        }
      });
    } else {
      formatData(entity[prop], level + 1);
    }
  } else {
    console.log(padString + prop + ':' + entity[prop])
  }
}

Answer №2

I may not be a pro, but I'll do my best to assist you here.

It looks like this information is being pulled from an external API, correct? It appears to me that the issue lies in how the data is being returned from the server. Have you considered using JSON.stringify to convert the object into a string?

It would be helpful to have insight into the type of data being transmitted from the server for better manipulation.

I hope this guidance proves beneficial to you...

Cheers

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

Looking for assistance with JQuery and JavaScript?

I oversee a team of employees, each with a 7-day work schedule. To streamline the process, I have developed a PHP form that I would like to use to collect data for verification in JavaScript before submitting it to an SQL database using AJAX. My main cha ...

Utilizing custom filters to navigate through nested ng-repeats

My goal is to achieve a specific behavior by using custom filters. I am working on creating a unified search bar that will display entire group names with all failing students, as well as group names with only the matching students. If you want to see the ...

learn to extract json information from a php web service using nsserialization

Currently, I am tackling json parsing using nsserialization. My aim is to parse a json data in uicollectionview. Below is the JSON API data I am working with: { "result": "Successful", "data": [ { "id": "2", "product_name": "6\" R ...

Add an event to your Fullcalendar with a date that is not the same as the present date in your MySQL database

I currently have Fullcalendar set up to display events from a MySQL table (title + datetime) and allow users to add new events by clicking on a specific day within the calendar. However, I am facing an issue where it only adds events to the current day ev ...

How to Trigger a Django View Using Ajax

I am working on integrating Ajax with Django to trigger an action upon button click. I have successfully invoked the JavaScript function, but I am facing issues in calling the Django view. Despite no errors being displayed, the print statement within my vi ...

AngularJS UI-Router: Utilizing Optional Parameters

.state('registration', { url:'/app/registration/:ref', templateUrl: 'partials/registration.html', }) This is my configuration for routing using ui-route. It functions properly when I go to localhost:80/r ...

Positioning oversized images in a React Native application

Looking to showcase two images side by side using React Native, where I can customize the screen percentage each image takes up. The combined size of the images will exceed the horizontal screen space available, so I want them to maintain their original di ...

Transferring image data to a different webpage

Currently, I am facing an issue with obtaining image data from a camera and photo album on a mobile device. Although I have successfully retrieved the chosen image using the provided code snippet below, my dilemma lies in transferring this image data to an ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

Tips for saving information from a textarea into an HTML file

I have a unique question regarding the usage of $fopen and $fwrite functions. My goal is to include a button named "save as HTML" below a textarea. Upon clicking this button, I want a popup box to appear mimicking the 'save as...' dialog window ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

Using regular expressions to validate input in Javascript

Seeking assistance to validate an input text using the pattern <some_string>:<some_string> in JS/JQuery. For instance: A110:B120 AB12C:B123 I understand this might seem overly simplistic, but any guidance would be greatly appreciated. ...

javascript with a focus on objects

Having trouble with the scene.add(Obj); line for my object player1. I keep getting an error saying that Obj does not exist: function Player(x, y, z) { this.Speed = 0; this.AngleAcc = 0; this.Angle = 0; this.X=x; this.Y=y; this.Z=z; this.MaxSpeed = ...

Issue with Jquery Slider Showing Empty Slide

Currently addressing issues with the slider on my site, which utilizes SlidesJS at . There seems to be a problem where it shows a blank slide inexplicably. After investigating, I noticed that a list element is being added to the pagination class, but I can ...

Send the information to MongoDB in the form of an object, utilize it as a query, and then perform

I have a document stored in my mongoDB database. https://i.sstatic.net/2DI2p.png When a user types something into an input field on the frontend, for example 'test', the object passed looks like this: {'countdown': 'test'} ...

Style the code presented within a div tag

I am in the process of creating a JavaScript-powered user interface that can generate code based on user interactions. While I have successfully implemented the code generation functionality and saved the generated code as a string, I am facing difficultie ...

Ways to incorporate a dynamic HTML form that allows for input elements to be added both horizontally and vertically while maintaining connected lines

Looking to design a form that showcases HTML elements in both vertical and horizontal positions, with lines connecting them as seen in this example: https://i.sstatic.net/jB12f.png. Can anyone offer guidance on how to achieve this? Thanks! ...

Extracting numbers using regular expressions can be tricky especially when dealing with mixed

Currently, I am attempting to create a javascript regex that can extract decimal numbers from a string containing a mix of characters. Here are some examples of the mixed strings: mixed string123,456,00indeed mixed string123,456.00indeed mixed string123,4 ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...