我想使用 Javascript 中的 JSON 檔案,我通過 Axios Get-Request 從我的 Flask 服務器獲得。
它的構建是這樣的:
{
"data": [
{
"item": "[224,4,1,80,207,137,153,132]",
"name": "A1"
},
{
"item": "[224,4,1,80,207,137,153,136]",
"name": "A2"
},
{
"item": "[224,4,1,80,207,137,157,190]",
"name": "A3"
}
]
}
我用這個提出我的請求,我可以在終端中看到輸出:
getInitialBoxesA() {
const path = 'http://localhost:5000/getAllBoxesA';
axios.get(path)
.then((res) => {
console.log(res.data);
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
},
我如何在 Javascript 中遍歷這個陣列?
我試過res.data[0]或res.data[0].item
uj5u.com熱心網友回復:
Axios 以res.data. 鑒于您的 JSON,您需要在res.data.data.
axios.get(path)
.then((res) => {
if (res.status === 200 && res.data?.data.length) {
for (obj of res.data.data) {
console.log(obj)
}
}
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
uj5u.com熱心網友回復:
試試這個
iterate(res.data.data);
function iterate(obj) {
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object") {
iterate(obj[key]);
} else console.log(`key: ${key}, value: ${obj[key]}`);
});
};
輸出
key: item, value: [224,4,1,80,207,137,153,132]
key: name, value: A1
key: item, value: [224,4,1,80,207,137,153,136]
key: name, value: A2
key: item, value: [224,4,1,80,207,137,157,190]
key: name, value: A3
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421946.html
標籤:
下一篇:如何使用div內的內容定位div
