Currently, I am working on Vue.js exercises that I have created. I am successfully populating a table with data from a JSON API, but I have encountered a challenge. The API contains multiple keys with similar names (strIngredient1, strIngredient2, strIngredient3, etc.), and some of these keys have null values. I am looking for a way to use regex during the mapping process to search for substrings like 'strIngredientx' where x is a number, and to exclude the null values. Below is the code I have been working on:
Ingredient.vue (parent):
<template>
<div>
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Category</th>
<th scope="col">strIBA</th>
<th scope="col">Ingredients</th>
</tr>
</thead>
<tbody>
<tr v-for="item in all_cocktails" v-bind:key="item">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.strIBA }}</td>
<td>{{ item.category }}</td>
<td><subComponent :item="item"></subComponent></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import subComponent from "./subComponent";
import axios from "axios";
export default {
data() {
return {
loading: false,
all_cocktails: {},
};
},
components: {
subComponent,
},
async mounted() {
this.loading = true;
await this.getData();
},
computed: {},
methods: {
getData() {
axios
.get(
"https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita"
)
.then((response) => (this.all_cocktails = response.data.drinks))
.then(
(response) =>
(this.all_cocktails = this.all_cocktails.map((d) => ({ //using map to pick the keys that I want.
id: d.idDrink,
name: d.strDrink,
category: d.strCategory,
strIBA: d.strIBA,
Ingredients: [ //here is there a way to loop for substring and not null instead of going through all of them ?
d.strIngredient1,
d.strIngredient2,
d.strIngredient3,
],
})))
)
.catch((error) => console.log(error))
.finally(() => (this.loading = false));
},
},
};
</script>
<style>
</style>
subComponent.vue (child):
<template>
<div>
<select>
<option
v-for="(item, index) in item.Ingredients"
:key="index"
v-bind:value="item"
>
{{ item }}
</option>
</select>
</div>
</template>
<script>
export default {
props: {
item: {},
},
data() {
return {};
},
};
</script>