๐Ÿ“– JavaScript Destructuring

Destructuring is a convenient way to extract values from arrays or properties from objects and assign them to variables. It simplifies the process of working with complex data structures in JavaScript and enhances code readability and maintainability.

Task

The task is to understand and implement destructuring in your JavaScript code. Destructuring allows you to extract multiple values in a single statement, making your code cleaner and more efficient. This is especially useful when dealing with APIs, data manipulation, and configuration objects. In the context of your recipe app project, destructuring can be applied when handling ingredients, recipe details, or categories.

Core Principles

Destructuring can be used with both arrays and objects. The syntax is concise and can include default values, renaming, and nested structures. It's important to understand the basics of arrays and objects before diving into destructuring.

Destructuring is especially useful when working with data like recipe objects, where you might want to access specific properties or values directly. By using destructuring, you can streamline your code and make it easier to manage dynamic data structures.

Coding Examples

Array Destructuring


// Basic array destructuring
const fruits = ['apple', 'banana', 'cherry'];
const [first, second] = fruits;

console.log(first); // Outputs: apple
console.log(second); // Outputs: banana
    

In this example, the array fruits is destructured, and the first two elements are assigned to the variables first and second.

Object Destructuring


// Basic object destructuring
const recipe = {
    name: 'Pasta Salad',
    servings: 4,
    ingredients: ['pasta', 'tomatoes', 'olive oil']
};

const { name, servings, ingredients } = recipe;

console.log(name); // Outputs: Pasta Salad
console.log(servings); // Outputs: 4
console.log(ingredients.join(', ')); // Outputs: pasta, tomatoes, olive oil
    

Here, the recipe object is destructured, extracting the name, servings, and ingredients properties into separate variables. The .join() method is used to convert the ingredients array into a string, with each ingredient separated by a comma and a space. This is useful when you want to display the array values in a human-readable format.

Putting It Into Action


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Destructuring Example</title>
</head>
<body>
    <script>
        const recipe = {
            name: 'Pasta Salad',
            servings: 4,
            ingredients: ['pasta', 'tomatoes', 'olive oil']
        };

        const { name, servings, ingredients } = recipe;

        document.body.innerHTML = `
        <div class="col-md-4">
            <div class="card mb-3">
                <div class="card-body">
                    <h5 class="card-title">${name}</h5>
                    <p>Servings: ${servings}</p>
                    <p>Ingredients: ${ingredients.join(', ')}</p>
                </div>
            </div>
        </div>
    `;
    </script>
</body>
</html>

This example shows how to use destructuring to dynamically extract and display recipe information. You'll see this pattern used in the Menu App when working with recipes or categories.

Challenge

Refactor the example to allow users to filter recipes by ingredients. The goal is to update the display based on the userโ€™s selection. Here are the steps:

Step 1:
Add an input field for the user to enter an ingredient.
Step 2:
Filter the recipes based on whether the entered ingredient is included in each recipeโ€™s ingredients list.
Step 3:
Update the displayed recipes to show only those that match the selected ingredient.

In order to check your learning, you should attempt to create a solution before revealing the provided solution below.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Recipe Filter Challenge</title>
</head>
<body>
    <h2>Filter Recipes by Ingredient</h2>
    <input type="text" id="ingredientInput" placeholder="Enter an ingredient">
    <button id="filterButton">Filter Recipes</button>
    <div id="recipeContainer" class="mt-3"></div>

    <script>
        const recipes = [
            {
                name: 'Pasta Salad',
                servings: 4,
                ingredients: ['pasta', 'tomatoes', 'olive oil']
            },
            {
                name: 'Fruit Smoothie',
                servings: 2,
                ingredients: ['banana', 'strawberries', 'yogurt']
            }
        ];

        const displayRecipes = (recipesArray) => {
            document.getElementById('recipeContainer').innerHTML = recipesArray.map(({ name, servings, ingredients }) => `
                <div class="col-md-4">
                    <div class="card mb-3">
                        <div class="card-body">
                            <h5 class="card-title">${name}</h5>
                            <p>Servings: ${servings}</p>
                            <p>Ingredients: ${ingredients.join(', ')}</p>
                        </div>
                    </div>
                </div>
            `).join('');
        };

        document.getElementById('filterButton').addEventListener('click', () => {
            const filterValue = document.getElementById('ingredientInput').value.trim().toLowerCase();
            const filteredRecipes = recipes.filter(({ ingredients }) => ingredients.includes(filterValue));
            displayRecipes(filteredRecipes);
        });

        // Display all recipes initially
        displayRecipes(recipes);
    </script>
</body>
</html>
                

References