在React中遍历对象

琼·班

我的代码中包含以下伪数据:

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
    }
  }

在我的组件之一上,我尝试对amenities属性进行迭代,因此尝试了以下代码:

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> 

如果键的值为true,则不会显示段落键。

它仅在HTML上显示空白。知道是什么原因造成的吗?

英国沙伦

使用map代替forEach

              { 
                  Object.entries(amenities).map(
                    ([key, value]) => {
                        return value ? <p>${key}</p> : null;
                    })
               }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章