Home > Software engineering >  How to filter an object using computed property and props [VueJS]
How to filter an object using computed property and props [VueJS]

Time:10-22

Firstly, thanks in advance for reading and helping out.

I am a bit lost trying to solve this. I currently have two Dropdown components which renders different options from an object. Im rendering two dropdowns. The second dropdown will depend on the selection of the first dropdown.

Let's say I select "BMW" in the first dropdown, and it should only render "BMW 320i".

The data object looks like this:

{
   "menu":[
      {
         "id":"bmw",
         "name":"BMW"
      },
      {
         "id":"volvo",
         "name":"Volvo"
      }
   ],
   "cars":[
      {
         "id":"bmw320",
         "name":"BMW 320i"
      },
      {
         "id":"volvoc70",
         "name":"Volvo C70"
      }
   ]
}

In my template I have two child components which include the dropdown. The MenuDropdown includes the dataContent.menu content, and CarDropdown includes dataContent.cars content.

<MenuDropdown :dataContent="dataContent">
<CarDropdown :dataContent="customDataContent">

The options of the CarDropdown will change depending on the selection of the first dropdown (MenuDropdown). So I am trying to achieve this by using a computed property:

computed: {
    customDataContent() {
        if (this.dataContent.menu.id === "bmw") {
            return this.dataContent.cars.filter(car => {
                return car.id === 'bmw320'
            })
        } else {
            return this.dataContent
        }
    }
}

Thanks for the help!

CodePudding user response:

the filter method returns an array, index it with [0] or use Array.find() instead

With find

return this.dataContent.cars.find(car => car.id === 'bmw320')

With filter

return this.dataContent.cars.filter(car => car.id === 'bmw320')[0]
  • Related