P

Using Vue watchers to format flat JSON

While tinkering with TheCocktailDB API, I noticed that it returned a single JSON object, ex:

... 
strIngredient1 "Bourbon"
strIngredient2 "Dark rum"
strIngredient3 "Heavy cream"
strIngredient4 null
...

Endpoint: https://www.thecocktaildb.com/api/json/v1/1/random.php

It returns NULL properties too. Passing this JSON object to a Vue component to parse and render would be clunky at best. So instead of dealing with this flat JSON, we can use watchers to parse and format it much more effeciently!

Imagine you have a main component that makes an AJAX request to the endpoint and recieves the JSON, naturally you assign it within your data object.

axios.get('https://www.thecocktaildb.com/api/json/v1/1/random.php') 
.then((response) => {
this.drinkData = response.data.drinks[0];
})
data: function() {
    return {
        drinkData: {}
    }
}

For simplicity sake, I will only focus on the strIngredient properties. Now lets add an empty array to our data object to only contain the ingredients

data: function() {
    return {
        drinkData: {},
        ingredients: []
    }
}

Now we can create a new watcher, to iterate over our flat JSON and push ingredients to the array. We simply pass our drinkData object and give it a function to execute when it's populated

watch: {
    drinkData: function() {
        for (let [key, value] of Object.entries(this.drinkData)) {
            if (value) {
                if (key.includes('strIngredient')) this.ingredients.push(value)
            }
        }
    }
}

We use Object.entries to grab the keys and values from the drinkData object, loop over them, only consider non null entries, and if the key contains 'strIngredient', we push the value, voila!