Home > database >  Map function, set index from and index to
Map function, set index from and index to

Time:09-01

Is it possible set index of function/method map()? Do not render all cars, but cars e.g. from id 2 to id 4. Example with 5 cars and render with component <View> and <Text> from library "@react-pdf/renderer": "2.3.0".

{
  "cars": [
    {
      "id": "0",
      "brand": "Toyota",
      "type": "Corolla",
      "color": "white"
    },
    {
      "id": "1",
      "brand": "Mazda",
      "type": "CX-30",
      "color": "red"
    },
    {
      "id": "2",
      "brand": "Honda",
      "type": "Civic",
      "color": "brown"
    },
    {
      "id": "3",
      "brand": "Audi",
      "type": "A6",
      "color": "black"
    },
    {
      "id": "4",
      "brand": "Mercedes",
      "type": "GLC",
      "color": "grey"
    }
  ],
  "total": 5
}

{data?.cars.map((car: any, index: number) => {
  return (
    <View 
      key={index}
    >
      <Text>{index   1}</Text>
      <Text>{car.brand || ""}</Text>
      <Text>{car.type || ""}</Text>
      <Text>{car.color || ""}</Text>
    </View>
  )
}

With for loop is not works.

{(() => {
  return (
    for (let j = 2; j < 5; j  ) {  // <--- Unreachable code
      <View 
        key={j}
      >
        <Text>{j   1}</Text>
        <Text>{car.brand || ""}</Text>
        <Text>{car.type || ""}</Text>
        <Text>{car.color || ""}</Text>
      </View>
    }
  )
})()}

I use typescript and reactjs 17.0.2.

CodePudding user response:

You can use slice method, data?.cars.slice(2).map to slice the array from index 3 ( the element whose has id = 2 ) to the rest of the array ( as the element whose id = 4 is the last element in the array ).

{data?.cars.slice(2).map((car: any, index: number) => {
  return (
    <View 
      key={index}
    >
      <Text>{car?.brand : ""}</Text>
      <Text>{car?.type : ""}</Text>
      <Text>{car?.color : ""}</Text>
    </View>
  )
}

CodePudding user response:

There are a couple of ways of doing this:

  1. Use a Array.filter:
{data?.cars.filter(car => parseInt(car.id) >= 2 && parseInt(car.id) <= 4).map((car: any, index: number) => {
  return (
    <View 
      key={index}
    >
      <Text>{car?.brand : ""}</Text>
      <Text>{car?.type : ""}</Text>
      <Text>{car?.color : ""}</Text>
    </View>
  )
}
  1. You use a ternary operator (conditional rendering) in the map:
{data?.cars.map((car: any, index: number) => {
  return (parseInt(car.index) >= 2 && parseInt(car.index) <= 4) ? (
    <View 
      key={index}
    >
      <Text>{car?.brand : ""}</Text>
      <Text>{car?.type : ""}</Text>
      <Text>{car?.color : ""}</Text>
    </View>
  ) : </>
}

Note: I would use card.index as key and not the index in the array. Something like this:

.map(car: any => {
  return (
    <View 
      key={car.index}
    >
      <Text>{car?.brand : ""}</Text>
      <Text>{car?.type : ""}</Text>
      <Text>{car?.color : ""}</Text>
    </View>
  )
  • Related