React.js Select with linked tables

Viewed 29

I want to create a select input where user can choose category, but it shows duplicate categories for every item in the database.

My json(there are more data):

[{"id":"1","title":"Book111","body":"111Texttexttexttexttexttexttexttext","price":"100.0","created_at":"2020-10-04T14:09:34.082Z","updated_at":"2020-10-15T13:49:30.454Z","category_id":"2","category":{"id":"2","name":"Books","created_at":"2020-10-04T14:09:10.181Z","updated_at":"2020-10-04T14:09:10.181Z"}},{"id":"3","title":"Movie1111","body":"Texttexttexttexttexttexttext","price":"100.0","created_at":"2020-10-04T14:10:08.698Z","updated_at":"2020-10-15T13:49:37.606Z","category_id":"1","category":{"id":"1","name":"Movies","created_at":"2020-10-04T14:09:02.143Z","updated_at":"2020-10-04T14:09:02.143Z"}}]

Code:

 var products = props.products.map((product) => {
  return(
    
 <option key={product.id} value = {product.category_id}>{product.category.name}</option>
        
  )
})

<select ref={input => formFields.category_id = input}  required >
              <option value = "">None</option>
              {products}
 </select>

So now my select look like : none, books, movies, movies, books.

1 Answers

An easy method to remove duplicates and generate a unique collection of category names (which I interpret as your goal) is by instantiating a new Set object from array of product category names, as shown below. To continue using .map to produce the options, create a new array from the Set.

    const catNameArr = Array.from(new Set(productJson.map(p => p.category.name)))
    /* .map over category name array to generate option els */
Related