【发布时间】:2020-04-28 12:30:49
【问题描述】:
我如何能够遍历这个 JSON api 响应以从“Incident_updates”数组中获取“body”对象?
这是 JSON:
[
{
"id": 3787,
"title": "Dummy title!",
"start_time": "2020-04-25T16:54:00.000Z",
"created_at": "2020-04-25T17:22:13.315Z",
"updated_at": "2020-04-25T17:32:15.364Z",
"incident_updates": [
{
"id": 9905,
"body": "Dummy Paragraph test!",
我尝试在我的 script.js 文件中使用 .map 和 foreach,但无论我尝试做什么,似乎都没有任何效果,并且我在控制台中收到“未定义的未定义”错误。我还需要从 api 响应中的所有数组中获取 event_updates.body 响应。做类似 event_updates[0].body 的工作,但是我还需要 event_updates[1].body 等的响应。
这是我的 script.js 文件
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error("ERROR");
}
return response.json();
})
.then((data) => {
console.log(data);
const html = data
.map((item) => {
console.log(item.incident_updates[0]);
return `<div class="card card-space">
<div class="card-body">
<h5 class="card-title">${item.title}</h5>
<h6 class="card-subtitle mb-2 text-muted">${item.start_time}</h6>
<p class="card-text">${item.incident_updates.body}</p> // issues with this
</div>
</div>`;
})
.join("");
感谢您的帮助!
【问题讨论】:
-
incident_updates是一个对象数组,您需要使用item.incident_updates[0].body检索其中一项。如果它有多个元素,您应该考虑创建另一个循环并检索它们。 -
您还需要迭代
item.incident_updates。您希望每个在您正在构建的 HTML 中如何显示? -
@HaoWu 我怎么能做一个 forEach 循环?
-
@AyushLal 我已经发布了一个答案,请检查它是否是你要找的。span>
-
@HaoWu 我已经回复你了
标签: javascript json