您好,當我列印沒有 id 的 jsonArray 時,我在 json 過濾方面遇到了一些問題, (jsonArray)通常會向我列印物件,但是當我添加 .id 時,(jsonArray.id)它說undefined我做錯了什么?
我得到的物件jsonArray,我只想列印它的“id”
{id: 39497866969165, product_id: 6677529493581, title: '8', price: '181.50'}
const api_url= 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele){
return ele.title == "8";
});
console.log(jsonArray.id)
}
getID();
uj5u.com熱心網友回復:
jsonArray 是陣列而不是物件。getID 是一個異步函式。它會回報承諾。你需要打電話給結果。
const api_url = 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele) {
return ele.title == "8";
});
const tmp_obj = {
id: jsonArray[0].id,
product_id: jsonArray[0].product_id,
title: jsonArray[0].title,
price: jsonArray[0].price
}
//console.log(tmp_obj)
return tmp_obj
}
getID().then(result => console.log(result));
uj5u.com熱心網友回復:
這是因為這里的 jsonArray 是一個串列而不是單個物件。
首先檢查它的長度以確保過濾器后至少有一個物件并通過以下方式記錄第一個元素:
if (jsonArray.length > 0) {
console.log(jsonArray[0].id)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366623.html
標籤:javascript json 过滤
上一篇:當您不知道Swift中的專案是哪種型別時,如何解碼嵌套的JSON資料?[復制]
下一篇:捕獲Json未知欄位的例外
