【问题标题】:I am trying to loop through an array and find each object that has said keyword in a property我正在尝试遍历一个数组并找到在属性中说过关键字的每个对象
【发布时间】:2019-12-14 13:30:03
【问题描述】:

所以我想将此变量设置为数组中的所有对象,其中其类别具有特定关键字。 这就是我目前所拥有的

  let tempMensProducts = tempClothingProducts
          .filter(obj => obj.category.includes('Mens'))

export const clothingProducts = [
  {
    id: 1,
    title: 'COMME DES GARCONS TEE',
    img: 'img/product-1.png',
    img2: 'img/product-1-1.png',
    img3: 'img/product-1-2.png',
    img4: 'img/product-1-3.png',
    luxury: 'All Luxury items are inspected to verify authenticity',
    price: 200,
    info: ' COMME DES GARCONS PLAY BASIC LOGO TEE',
    inCart: false,
    count: 0,
    total: 0,
    fabric: '100% Cotton',
    category: 'Mens Fashion'
  }
]

【问题讨论】:

  • 请添加一些预期的输入和输出。
  • 嘿抱歉 ctrl k 只是搜索谷歌所以我必须在之后添加代码
  • 你能添加一些示例数据吗
  • 我没有对@TheGreenLightbulb 投反对票 - 请不要认为评论者是反对票的人。
  • @TheGreenLightbulb:兄弟放轻松,我刚刚恢复了我的反对意见。当没有看到样本和努力时,人们会否决这个问题。您添加了一些样本,现在一切正常。但很少有人会回来恢复它。但请记住,即使“男性”输入的类别是“女性时尚”,您标记为正确的答案也会返回 true

标签: javascript arrays reactjs object


【解决方案1】:

您需要将回调传递给map 才能使用它 - 但这里根本不需要map。只需使用filter

let tempMensProducts = tempClothingProducts.filter(({ category }) => category.includes("Mens"));

如果你尝试在没有回调的情况下使用map,它会在尝试调用其参数时导致错误,如果你不传递一个,它会尝试执行undefined()

[1, 2, 3].map();

【讨论】:

  • 好让我看看变量的输出是什么
  • 嘿,我如何在语句中添加或
  • 让 tempMensProducts = tempClothingProducts.filter(({ category,description }) => category.includes("Mens") description.includes("description"));
  • 这样的
  • 只是一个想法,它也将匹配“女性时尚”类别,因为那里也有“男性”
【解决方案2】:

您可以用空格分割数组,然后在此处应用数组contains 以确保它会给您正确的结果

我的意思是说当关键字是“男人”时它不应该返回“女人”

let clothingProducts = [
  {
    id: 1,
    title: 'COMME DES GARCONS TEE',
    img: 'img/product-1.png',
    img2: 'img/product-1-1.png',
    img3: 'img/product-1-2.png',
    img4: 'img/product-1-3.png',
    luxury: 'All Luxury items are inspected to verify authenticity',
    price: 200,
    info: ' COMME DES GARCONS PLAY BASIC LOGO TEE',
    inCart: false,
    count: 0,
    total: 0,
    fabric: '100% Cotton',
    category: 'Mens Fashion'
  },
  {
    id: 2,
    title: 'COMME DES GARCONS TEE',
    img: 'img/product-1.png',
    img2: 'img/product-1-1.png',
    img3: 'img/product-1-2.png',
    img4: 'img/product-1-3.png',
    luxury: 'All Luxury items are inspected to verify authenticity',
    price: 200,
    info: ' COMME DES GARCONS PLAY BASIC LOGO TEE',
    inCart: false,
    count: 0,
    total: 0,
    fabric: '100% Cotton',
    category: 'woMens Fashion'
  }
  ]
   let filter = clothingProducts.filter(c => c.category.split(" ").includes("Mens"));
  console.log(filter);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 2021-11-15
    • 2017-02-15
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多