我有一個函式呼叫另一個函式從 axios 獲取資料。我無法遍歷 json 物件的陣列。它顯示為未定義,我不確定為什么?
最終功能:
async function final(){
let final = []
let data1 = await getPeople();
let data2 = await getXml();
for(i=0;i<data1.length;i ){
final.push(data1[i]);
}
console.log(data2.persons.person)
for(j=0;j<data2.persons.person.length;j ){
final.push(data2[j])
}
final.sort();
return final;
}
獲取xml函式:
async function getXml(){
let ans;
const {data} = await axios.get('https://gist.githubusercontent.com/SwayamShah97/a3619c5828ac8ed8085c4ae295a855d9/raw/e4e372552e042bd8bd9e8ab87da93eb030114f86/people.xml');
xml2js.parseString(data, (err, result) => {
if(err) {
throw err;
}
const json = JSON.stringify(result, null, 4);
ans = json
});
return ans;
}
我從 xml 函式中正確獲取了資料,但是如何遍歷人?
uj5u.com熱心網友回復:
您的代碼有幾個問題。首先,您不想對 xml2js 決議的結果進行字串化。您希望將其保留為 JavaScript 物件。
其次,您不會在結果中迭代正確的節點。您正確記錄它,但隨后您遍歷父節點。這是對您的代碼的最小修復:
import axios from 'axios';
import xml2js from 'xml2js';
async function getXml() {
let ans;
const { data } = await axios.get('https://gist.githubusercontent.com/SwayamShah97/a3619c5828ac8ed8085c4ae295a855d9/raw/e4e372552e042bd8bd9e8ab87da93eb030114f86/people.xml');
xml2js.parseString(data, (err, result) => {
if (err) {
throw err;
}
// const json = JSON.stringify(result, null, 4);
ans = result;
});
return ans;
}
async function final() {
const final = [];
// const data1 = await getPeople();
const data2 = await getXml();
// for (let i = 0; i < data1.length; i ) {
// final.push(data1[i]);
// }
console.log(data2.persons.person);
for (let j = 0; j < data2.persons.person.length; j = 1) {
final.push(data2.persons.person[j]);
}
final.sort();
return final;
}
console.log(await final());
還有其他可以清理的東西,但這會讓你繼續前進。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/432065.html
下一篇:圖片在本地顯示但不顯示在服務器上
