如何使用单个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循环?将多个循环嵌套在一起并不被认为是“错误的”。此外,您的代码将根据您要搜索的内容而有所不同... –