Skip to content
Advertisement

Map only a particular object based on ID in Typescript

I have an array of objects, which looks like:

const cartItems = [
  {
    id: 1,
    new1: "Hello",
    new2: "New hello"
  },
  {
    id: 2,
    new1: "Hello",
    new2: "New hello"
  },
  {
    id: 3,
    new1: "Hello",
    new2: "New hello"
  }
];

I am currently using this array of objects to map over all items like this:

cartItems.map(product => (
    <React.Fragment key={product.id}>
        <p>{product.new1}</p>
    </React.Fragment>
));

This loops over all the products, but I would like to have this code limited to one particular product. Like with ID=3 or whatever I supply.

cartItems.find(product => product.id === 3)

The above code helps me find it, but I cannot map over it to loop and write some React UI on it. Any help here is appreciated.

Advertisement

Answer

the find() function only returns a single item and not an array of items. If you would like to iterate you need an array with an single item. This can be done using the filter() function.

cartItems.filter(product => product.id === 3).map(item => (
  // Your React stuff
))

as alterative you can access the properties directly when using the find() function.

{const singleCardItem = cartItems.find(product => product.id === 3)}
<p>singleCardItem.new1</p>

find() Documentation

filter() Documentation

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement