簡體   English   中英

在Javascript中循環對象的JSON數組

[英]Loop through JSON array of objects in Javascript

我有這個函數從 API 返回一個對象數組,如下所示:

data: Array(4)
0: {city: 'Aberdeen', state: 'Maryland'}
1: {city: 'Aberdeen', state: 'Mississippi'}
2: {city: 'Aberdeen', state: 'South Dakota'}
3: {city: 'Aberdeen', state: 'Washington'}

這是迄今為止的功能:

function search(data) {
    fetch(`[url omitted]/?city=${data}`)
      .then((res) => res.json())
      .then((resjson) => console.log(resjson));
  }

我怎樣才能通過這個循環才能在頁面上顯示結果? 我試過 for 循環

for(let i = 0; i < resjson.length; i++) {
    let obj = resjson[i];

    console.log(obj.id);
}

和這個

resjson.forEach(function(obj) { console.log(obj.id);

這些都沒有奏效。 有人可以解釋我做錯了什么以及如何解決這個問題嗎?

謝謝

您正在注銷不存在的id屬性,因此它將打印出undefined 嘗試安慰citystate

 const resjson = [ { city: "Aberdeen", state: "Maryland" }, { city: "Aberdeen", state: "Mississippi" }, { city: "Aberdeen", state: "South Dakota" }, { city: "Aberdeen", state: "Washington" }, ]; resjson.forEach(function (obj) { console.log(obj.state); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM