Home > Software design >  How can I pretty print keys and values of a JavaScript object on web page
How can I pretty print keys and values of a JavaScript object on web page

Time:04-01

I have a JavaScript object that contains terms and definitions. I want to create a function that displays/prints the key, value pairs on a webpage.

For example:

let dict = {
    term1: "definition",
    term2: "definition",
    term3: "definition",
    term4: "definition"
}

Ideal output:

term1: definition

term2: definition

term3: definition

term4: definition

I am currently using this code:

function viewAll()
{
var json = JSON.stringify(dict,null,3);
document.getElementById("output").innerText = json;
}

which outputs:

{
term1: "definition",
term2: "definition",
term3: "definition",
term4: "definition"
}

This is okay, but I'd like to remove the special characters ({",)

CodePudding user response:

Us Object.entries and map to format the data how you want to display it.

let dict = {
    term1: "definition 1",
    term2: "definition 2",
    term3: "definition 3",
    term4: "definition 4"
}

const str = Object.entries(dict).map(([key, value]) => `${key}: ${value}`).join("<br/>");

document.getElementById("out").innerHTML = str;
<div id="out"></div>

Seems like you really want a definition list

let dict = {
  term1: "definition 1",
  term2: "definition 2",
  term3: "definition 3",
  term4: "definition 4"
}

const str = Object.entries(dict).map(([key, value]) => `<dt>${key}</dt><dd>${value}</dd>`).join('');

document.getElementById("out").innerHTML = str;
dt::after {
  content: ":"
}

dt {
  display: inline-block;
}

dd {
  display: inline;

}

dd:after {
  content: '';
  display: block;
}
<dl id="out"></dl>

  • Related