以下 JSON 從 API 回傳給我
[
{
type: 'atom',
id: 'atom',
atom: { type: 'priceWithTitle', priceWithTitle: [Object] }
},
{
type: 'atom',
id: 'atom',
atom: { type: 'price', price: [Object] }
},
{
type: 'atom',
id: 'name',
atom: { type: 'textAtom', textAtom: [Object] }
},
{ atom: { type: 'labelList', labelList: [Object] } }
]
簡要地說我如何獲得這些資料:
......
const JsonFromApi = JSON.parse(DataFromApi)
console.log(JsonFromApi)
// After that I get Json from above
要參考一組特定的元素,我需要指定它。例如,為了獲取我需要的塊(其中包含價格,它是連續第二個),我需要指定[1],例如
console.log(JsonFromApi[1]) // After that I get the element I need, below will be the json i get:
{
type: 'atom',
id: 'atom',
atom: {
type: 'price',
price: {
price: '532 $',
priceColor: 'amTextSecondary',
originalPriceColor: 'amTextSecondary',
theme: 'STYLE_TYPE_MEDIUM',
strikethroughColor: 'amAccentAlert'
}
}
}
所以有什么問題?
API回傳給我的JSON可以改變里面元素的順序,比如我現在用[1]申請一個產品的價格,下次或者用另一個產品,元素會是[2] , [3] 或其他。
問題 - : 如果元素的順序不斷變化,如何獲取我需要的資料,唯一的線索是 -> atom: { type: 'price', price: [Object] }
type:包含里面資料型別的型別資訊,如何先檢查哪個元素包含我需要的型別,然后獲取它的值,例如->獲取商品的價格?
uj5u.com熱心網友回復:
您可以在原子物件上使用函式 hasOwnProperty()
const object = [
{
type: "atom",
id: "atom",
atom: { type: "priceWithTitle", priceWithTitle: [Object] },
},
{
type: "atom",
id: "atom",
atom: { type: "price", price: [Object] },
},
{
type: "atom",
id: "name",
atom: { type: "textAtom", textAtom: [Object] },
},
{ atom: { type: "labelList", labelList: [Object] } },
];
function checkPrice(object) {
object.forEach((element) => {
if (element.atom.hasOwnProperty("price")) {
console.log(element.atom.price);
}
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/519944.html
