How to to print nested [object Object] without affecting other types

147 Views Asked by At

I am currently trying to show some data on my webpage (not the console, actually inject it into a paragraph) which (for example) looks as follows:

["accept", "#PID<0.395.0>", {"id": "N1", "num": 1}, "Appeltaart"]

The way I would like to print this is:

[accept, #PID<0.395.0>, {id: N1, num: 1}, Appeltaart]

However, the way I get it printed now when I do no pre-processing is:

accept, #PID<0.395.0>,[object Object], Appeltaart

Note that my nested Objects now are not converted to a string and my original list also disappeared. When I print it using the JSON.stringify() beforehand, I get the following:

["accept", "#PID<0.395.0>", {"id": "N1", "num": 1}, "Appeltaart"]

Note that around every value there are now quote (") symbols. How would I achieve the result I desire?

1

There are 1 best solutions below

0
Andrew Parks On

You can create a custom object printer like this:

function printObj(v) {
  if(typeof v === 'object') {
    return Array.isArray(v) ? 
      `[${v.map(i=>typeof i==='object' ? printObj(i) : i).join(', ')}]` : 
      `{${Object.entries(v).map(([k,v])=>`${k}: ${v}`).join(', ')}}`
  }
  else return v
}

const arr = ["accept", "#PID<0.395.0>", {"id": "N1", "num": 1}, "Appeltaart"]

console.log(printObj(arr))