Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove a string using Ternary operation in JavaScript

I have something like this in my console: How can I take out the [object Object] from my output?

I want the output printed without the [Object Object]. Probably using a ternary operation?

id:4fe2ce6467ca126064231husklpjahjjkk 
url:http://8000/v1/data/country/
type:country
name:South Africa
legal:[object Object]
  text:Data is supplied by Government
  link:https://en.wikipedia.org/

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 want something like:

>Solution :

The following test will always pass because typeof true and typeof false are both "boolean" which is truthy.

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

Try

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

I have no idea why you are talking about a ternary operation.


To avoid the [object Object] you can move the existing console.log and add another one as shown:

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])
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading