簡體   English   中英

如何遍歷 Javascript 中的 JSON 對象數組?

[英]How do I iterate through an array of JSON objects in Javascript?

類似措辭的問題已經在這里多次提出,但似乎沒有一個能幫助我解決我的問題。 我正在處理從 API (PokeAPI) 中提取的 JSON 數據,並且我已將此數據存儲在 Javascript 中的 object 中。據我了解,這會將 JSON 數據存儲在一個數組中, Console.log(myData)會產生我Chrome 控制台中的以下內容:

控制台 output 全數據

我想構建一個表來布置數組中每個對象中的一些數據。 我以為我可以通過簡單地使用諸如myData[0].name之類的代碼來訪問每個 object 中的任何字段,但這是失敗的。 嘗試執行Console.log(myData[0])只會返回未定義的 object。如何迭代訪問我想要的數據?

我目前的嘗試如下所示:

function getData(inputData) {
var data = [];
    for (i = 0; i < inputData.length; i++) {
        data[i] = [
            inputData[i].id,
            inputData[i].name,
            inputData[i].height,
            inputData[i].weight,
            inputData[i].type[0],
            inputData[i].base_experience];
}

console.log(inputData); //Returns all the data
console.log(inputData[0]); //Returns undefined
return data;

編輯:一些評論詢問我如何從 API 獲取數據。這是:

function fetchData(endpoint_URL) {
$.ajax({
    url: base_URL + endpoint_URL,
    dataType: "json",
    success: function (response) {
        //console.log(response);
        let p = new Promise((resolve, reject) => {
            successHandler(response);
            if(dataSet != null) {
                //console.log(dataSet);
                resolve('Success');
            } else {
                reject('Failed');
            }
        })
        
        //console.log(dataSet);
        p.then((message) => {
            //console.log(dataSet);
            loadTableData(dataSet)
        }).catch((message) => {
            console.log("Data fetch unsuccessful");
        })
    },
    error: function(request, status, error){
        console.log(status);
    }
});


function successHandler(response) {
    dataSet = [];
    interimData = [];
        for (var i in response.results) {
            interimData[i] = response.results[i];
            //console.log(response.results[i]);
            //console.log(dataSet[i]);
        }
        //console.log(interimData);

        for (let i = 0; i<interimData.length; i++) {
            $.ajax({
                url: interimData[i].url,
                dataType: "json",
                success: function(details) {
                    dataSet[i] = details;
                }
            })
        };
        //console.log(dataSet);
};

數據集dataSet在任何 function(全局?)之外聲明,代碼為var dataSet=[]; . getData() function 在loadTableData()的第一行被調用

您可能遇到控制台顯示非同步數據的問題(“此值剛剛評估”消息)。 因此,這可能與您有關從 API 獲取數據的操作有關,如果是這樣,您可能會在 [0] 處控制台記錄 object,這在調用時是未定義的,因為此 function 在實際獲取數據。 整個 object 可能是 console.log-able,因為開發控制台行為會在您在控制台中單擊它時評估 object。

這是使用異步和等待的基本調用:

async function getDataAsync () {
  let fetchedData;
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => fetchedData = json);
  console.log(fetchedData.userId); // 1
  return fetchedData;
}

var result1 = await getDataAsync();
console.log(JSON.stringify(result1)); // {"userId":1,"id":1,"title":"delectus aut autem","completed":false}

這是一個使用Promise.all()的嵌套調用:

async function getDataWithOtherResultsAsync () {
  let fetchedData;
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => fetchedData = json);
  
  const otherUrlsToTry = ['https://jsonplaceholder.typicode.com/todos/2', 'https://jsonplaceholder.typicode.com/todos/3'];
  const otherUrlPromises = otherUrlsToTry.map(m => 
    new Promise(
      resolve =>
      fetch(m)
       .then(n => n.json())
       .then(json => resolve(json))
    )
  );

  const otherUrlResults = await Promise.all(otherUrlPromises);

  return { mainData : fetchedData, otherData : otherUrlResults };
}

var result2 = await getDataWithOtherResultsAsync();
console.log(JSON.stringify(result2));
/*
{
  "mainData":{"userId":1,"id":1,"title":"delectus aut autem","completed":false},
  "otherData":[
    {"userId":1,"id":2,"title":"quis ut nam facilis et officia qui","completed":false},
    {"userId":1,"id":3,"title":"fugiat veniam minus","completed":false}
  ]
}
*/

這只是 Vasily Hall 告訴您的附帶事實。

看起來你把一個數組放到了一個數組中:

function getData(inputData) {
   var data = [];
   for (i = 0; i < inputData.length; i++) {
    // data[i] is declared as Array:
    data[i] = [
        inputData[i].id,
        inputData[i].name,
        inputData[i].height,
        inputData[i].weight,
        inputData[i].type[0],
        inputData[i].base_experience];
}

試試這個:

function getData(inputData) {
var data = [];
for (i = 0; i < inputData.length; i++) {
    // bracelets makes it an object 
    data[i] = {
        inputData[i].id,
        inputData[i].name,
        inputData[i].height,
        inputData[i].weight,
        inputData[i].type[0],
        inputData[i].base_experience};

   // alternative you can use this:
   data.push({...inputData[i]});
  }

console.log(inputData); //Returns all the data
console.log(inputData[0]); //Returns undefined
return data;
}

暫無
暫無

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

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