Javascript 在React中遍历对象
我的代码中有以下虚拟数据:Javascript 在React中遍历对象,javascript,reactjs,Javascript,Reactjs,我的代码中有以下虚拟数据: const resorts = [ { _id: "1", name: "Lakawon Island Resort", price_per_night: 2804.0, description: "On a lush 16-hectare island with white-sand beaches, this relaxed resort is 5 km from t
const resorts = [
{
_id: "1",
name: "Lakawon Island Resort",
price_per_night: 2804.0,
description:
"On a lush 16-hectare island with white-sand beaches, this relaxed resort is 5 km from the jetty in Cadiz Viejo, a village on the mainland.",
address: "Cadiz Viejo",
city: "Cadiz",
province: "California",
zip_code: "6121",
latitude: 11.045411,
longitude: 123.201465,
contact_number: "(034) 213 6354",
website: 'www.lakawonislandresort.com',
amenities:
{
tv: false,
reservation: false,
moderate_noise: true,
free_wifi: true,
trendy: true,
credit_card: true,
bar: true,
animals: true,
kids: true
},
image:
"https://images.unsplash.com/photo-1512356181113-853a150f1aa7",
rating: 4.5,
reviews: 11,
},
{
_id: "2",
name: "Bluewater Maribago Beach Resort",
price_per_night: 4156,
description:
"Set in a complex of thatch-roofed buildings on the Cebu Strait, this posh beachfront resort is 1 km from Mactan Island Aquarium and 4 km from the Magellan Shrine.",
address: "Buyong",
city: "California",
province: "Maribago Mactan Island",
zip_code: "6015",
latitude: 10.290899,
longitude: 124.000822,
contact_number: "(032) 402 4100",
website: "http://www.bluewater.com.ph/",
image:
"https://images.unsplash.com/photo-1507525428034-b723cf961d3e",
rating: 3.5,
reviews: 35,
amenities:
{
tv: true,
reservation: true,
moderate_noise: false,
free_wifi: false,
trendy: false,
credit_card: false,
bar: true,
animals: true,
kids: true
}
}
在我的一个组件上,我尝试迭代便利设施
属性,因此我尝试了以下代码:
const { name, address, city, province, zip_code, image, description, amenities } = resortsList
<div>
{
Object.entries(amenities).forEach(
([key, value]) => {
if(value){
return `<p>${key}</p>`
}
}
)
}
</div>
const{姓名、地址、城市、省份、邮政编码、图像、描述、便利设施}=resortsList
{
对象。条目(便利设施)。forEach(
([key,value])=>{
如果(值){
返回`${key}`
}
}
)
}
如果键的值为true,则不显示段落键
它只显示我的HTML空白。你知道这是什么原因吗?用
map
代替forEach
{
Object.entries(amenities).map(
([key, value]) => {
return value ? <p>${key}</p> : null;
})
}
{
对象。条目(便利设施)。地图(
([key,value])=>{
返回值?${key}:null;
})
}
使用map
而不是forEach
{
Object.entries(amenities).map(
([key, value]) => {
return value ? <p>${key}</p> : null;
})
}
{
对象。条目(便利设施)。地图(
([key,value])=>{
返回值?${key}:null;
})
}