如何在网页上漂亮地打印 JavaScript 对象的键和值
How can I pretty print keys and values of a JavaScript object on web page
我有一个包含术语和定义的 JavaScript 对象。我想创建一个 displays/prints 网页上的键值对的函数。
例如:
let dict = {
term1: "definition",
term2: "definition",
term3: "definition",
term4: "definition"
}
理想输出:
term1: 定义
term2: 定义
term3: 定义
term4: 定义
我目前正在使用这个代码:
function viewAll()
{
var json = JSON.stringify(dict,null,3);
document.getElementById("output").innerText = json;
}
输出:
{
term1: "definition",
term2: "definition",
term3: "definition",
term4: "definition"
}
没关系,但我想删除特殊字符 ({",
)
我们 Object.entries 并映射以按照您想要的方式显示数据。
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>
看来你真的想要一个定义列表
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>
我有一个包含术语和定义的 JavaScript 对象。我想创建一个 displays/prints 网页上的键值对的函数。
例如:
let dict = {
term1: "definition",
term2: "definition",
term3: "definition",
term4: "definition"
}
理想输出:
term1: 定义
term2: 定义
term3: 定义
term4: 定义
我目前正在使用这个代码:
function viewAll()
{
var json = JSON.stringify(dict,null,3);
document.getElementById("output").innerText = json;
}
输出:
{
term1: "definition",
term2: "definition",
term3: "definition",
term4: "definition"
}
没关系,但我想删除特殊字符 ({",
)
我们 Object.entries 并映射以按照您想要的方式显示数据。
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>
看来你真的想要一个定义列表
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>