Object/Array Destructuring in javaScript with an API

Learn with API

Object Destructuring

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array and Object Destructuring Example</title>
</head>
<body>
    <div id="app">
        <h1>Users List</h1>
        <ul id="userList"></ul>
    </div>
    <script src="./src/script.js"></script>  <!--update path based on your file tree-->
</body>
</html>
// script.js

const userList = document.getElementById('userList');

// Fetch data from the API
fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(users => {
        // Loop through the users array
        users.forEach(user => {
            // Destructure user object to extract specific properties
            const { id, name, email, address: { city, zipcode } } = user;

            // Create list item for each user
            const listItem = document.createElement('li');
            listItem.innerHTML = `
                <strong>${name}</strong> - ${email}<br>
                City: ${city}<br>
                Zipcode: ${zipcode}
            `;
            userList.appendChild(listItem);
        });
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });

Object destructuring UI output

Array Destructurting in JavaScript

// script.js

const userList = document.getElementById('userList');

// Fetch data from the API
fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(users => {
        // Loop through the users array
        users.forEach(user => {
            // Destructure user object
            const { id, name, email } = user;

            // Create list item for each user
            const listItem = document.createElement('li');
            listItem.innerHTML = `<strong>${name}</strong> - ${email}`;
            userList.appendChild(listItem);
        });
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });

Array destructuring output in UI