I am working on using context in react applications. I am not sure how to describe what follows, but I am thinking maybe it is an object of arrays. My question is how I extract the title which contains the word, ‘hat’. This is just one item. Otherwise, it would contain more of these items that I would also extract. What I tried is: categoriesMap[0] and the like. Nothing worked. Thanks, Joshua.
categoriesMap[category] =
[
{
title: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
price: 25,
},
{
id: 2,
name: 'Blue Beanie',
imageUrl: 'https://i.ibb.co/ypkgK0X/blue-beanie.png',
price: 18,
},
{
id: 3,
name: 'Brown Cowboy',
imageUrl: 'https://i.ibb.co/QdJwgmp/brown-cowboy.png',
price: 35,
},
{
id: 4,
name: 'Grey Brim',
imageUrl: 'https://i.ibb.co/RjBLWxB/grey-brim.png',
price: 25,
},
{
id: 5,
name: 'Green Beanie',
imageUrl: 'https://i.ibb.co/YTjW3vF/green-beanie.png',
price: 18,
},
{
id: 6,
name: 'Palm Tree Cap',
imageUrl: 'https://i.ibb.co/rKBDvJX/palm-tree-cap.png',
price: 14,
},
{
id: 7,
name: 'Red Beanie',
imageUrl: 'https://i.ibb.co/bLB646Z/red-beanie.png',
price: 18,
},
{
id: 8,
name: 'Wolf Cap',
imageUrl: 'https://i.ibb.co/1f2nWMM/wolf-cap.png',
price: 14,
},
{
id: 9,
name: 'Blue Snapback',
imageUrl: 'https://i.ibb.co/X2VJP2W/blue-snapback.png',
price: 16,
},
],
},
];
2
Answers
Ah, I can't get the find to work, I get: categoriesMap.find is not a function. Perhaps because it is not a simple array? Would you continue to help me, please? Here is the code:
To extract the title that contains the word ‘hat’ from the categoriesMap, you can use the filter and find array methods. Here’s an example of how you can achieve that:
In this code, the find method is used to filter the categoriesMap array and find the category that has the title containing the word ‘hat’. If a matching category is found, its title and items can be accessed. Otherwise, if no matching category is found, an appropriate message can be displayed.
Remember to replace categoriesMap with the actual variable name you’re using in your code.