如何使用單個forin循環從json數據中搜索任何項目。 我曾嘗試搜索一個,但如果我想從其他領域搜索,該怎麼辦。 例如,如果我想搜索是否存在來自featuredBrands的項目並且存在是否返回該項目。如何搜索下面的json數據中的任何項目
var users = [{
"userProfile": {
"firstName": "Rahul",
"lastName": "Jhawar",
"cartitemsno": 2,
"items": ["THINK AND GROW RICH", "Lenovo Z2 Plus"]
}
},
{
"dayDeals": [{
"productCategory": "Sports & Fitness Gear",
"discount": "20-80% off",
"items": "Yonex,Li-Ning & more"
},
{
"productCategory": "Best Ethnic Trends",
"discount": "50-80% off",
"items": "Kurtas,Sarees & more"
},
{
"productCategory": "Popular Brands",
"discount": "60-80% off",
"items": "T-shirts,Shirts,Jeans"
}
]
},
{
"featuredBrands": [{
"brandName": "Ambrane",
"userRating": 3.7
},
{
"brandName": "Sony",
"userRating": 4.2
},
{
"brandName": "IPro",
"userRating": 4.0
}
]
},
{
"recommendedItems": [{
"itemName": "Stay Hungry Stay Foolish",
"productCategory": "Books",
"prouctPrice": "Rs 186",
"offer": "3%"
},
{
"itemName": "iPro IP 43 20800 mAh Power Bank (White & Grey, Lithium-ion)",
"productCategory": "Mobile Accessories",
"prouctPrice": "Rs 1199",
"offer": "60%"
},
{
"itemName": "Micromax Canvas Pulse 4G (Grey, 16 GB) (3 GB RAM)",
"productCategory": "Mobile Phones",
"prouctPrice": "Rs 11199",
"offer": "12%"
}
]
}
]
var displayitem = function(users, name) {
for (var item in users) {
if (users[item].userProfile.firstName == name) {
return users[item].userProfile.firstName;
} else {
return "Item not found"
}
}
};
console.log(displayitem(users, "Rahul"));
爲什麼你想只使用一個for循環?將多個循環嵌套在一起並不被認爲是「錯誤的」。此外,您的代碼將根據您要搜索的內容而有所不同... –