JSON数据转换成显示键和值的列表



我想使用从JSON中获得的数据创建一个列表,并动态填充ul

我的代码到目前为止

let userInfo = [];
const containerInfo = document.getElementById("result");
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response=> response.json())
.then(data => {
userInfo = data;
for(info in userInfo){
console.log(info)
let li = document.createElement("li");
let node = document.createTextNode(info)
li.appendChild(node)
containerInfo.appendChild(li)

}
console.log(userInfo.id)
})

预期输出:

userId: number
id: number
title: string
body: string

遗憾的是,我无法找到一种方法来获得两者,我尝试使用不同的方法,但我不知道如何有这种输出:

userId: 1
id: 1
title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
body: quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto

我可以在表格中手动放一个字符串但我想用javascript

创建一个动态的列表

您可以使用Object.entries()实现此功能。

下面是jsfiddle

中的一个示例
for(let [key,value] of Object.entries(userInfo)){
let li = document.createElement("li");
let node = document.createTextNode(key +': '+ value)
li.appendChild(node)
containerInfo.appendChild(li)
console.log(key +': '+ value)
}

最新更新