简体   繁体   中英

I am trying to loop through an array and find each object that has said keyword in a property

So I want to set this variable to all of the objects in an array in which its category has a certain keyword. This is what I have so far

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

You need to pass a callback to map to use it - but here, map isn't required at all. Just use filter .

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

If you try to use map without a callback, it'll result in an error as it tries to call its argument, and if you don't pass one, it'll try to do undefined() .

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

You can split the array by whitespaces and then apply array contains there to sure that it will give you correct result

I mean to say it should not return "Women" when keyword is "men"

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM