我正在使用如下所示的大型 JSON 檔案:
{
"name": "Superproduct",
"description": "Enjoy this amazing product.",
"brand": "ACME",
"categories": [
"Ball",
"Soccer Ball",
"Beach Ball"
],
"type": "Online product",
"price": 50,
"price_range": "50 - 100",
"image": "someImageURL",
"url": "SomeProductURL",
"free_shipping": true,
"popularity": 10000,
"rating": 2,
"objectID": "1234"
}
我正在嘗試使用Ball類別訪問每個物件,以便我可以為該特定專案添加折扣。我意識到每個物件在類別陣列中都可以有多個單詞Ball的變體。
有沒有辦法可以定位陣列中的單詞球,以便我可以將其添加到陣列中并將折扣應用于具有所述標準的每個產品?
這是我到目前為止所擁有的,但我不確定這是否是最好的方法,或者是否有更好的方法來完成我正在嘗試做的事情:
async function setDiscount() {
let discountedRate = 0.5;
fetch('products.json')
.then(res => res.json())
.then(data => {for (let i = 0; i < data.length; i ) {
if (data[i].categories[i] == "Ball") {
data[i].price -= (data[i].price * discountedRate);
}
}});
}
setDiscount();
PS:我是新手。
uj5u.com熱心網友回復:
您可以通過迭代回應陣列來簡單地實作這一點。
作業演示:
const data = [{
"name": "Superproduct",
"description": "Enjoy this amazing product.",
"brand": "ACME",
"categories": [
"Ball",
"Soccer Ball",
"Beach Ball"
],
"type": "Online product",
"price": 50,
"price_range": "50 - 100",
"image": "someImageURL",
"url": "SomeProductURL",
"free_shipping": true,
"popularity": 10000,
"rating": 2,
"objectID": "1234"
}];
const discountedRate = 0.5;
data.forEach((obj) => {
obj.price = obj.categories.includes('Ball') ? (obj.price * discountedRate) : obj.price
});
console.log(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431224.html
標籤:javascript json
