What method works most effectively for breaking down a large (nested) object?

My objective involves destructuring a large nested object and assigning its properties to variables. Currently, I am doing it this way:

const { name, country, sunrise, sunset, timezone } =
   this.state.weather?.city || {};
    
const { temp, feels_like } =
   this.state.weather.list?.[0].main || {};

Are there any alternative methods that could make this code more concise?

Answer №1

Edit:

Important points:

  1. Utilizing object destructuring:

    const data = { id: 1, name: "SO" }
    const { id, name, city = "N/A" } = data
    console.log(id, name, city);

  2. Employing array destructuring:

    const data = [ 1, 2 ]
    const [first, second, third = "N/A"] = data
    console.log(first, second, third)

  3. Managing array of objects using destructuring:

    const data = [ {id: 1, name: "SO"} ]
    const [ { id, name, city = "N/A" }, second = {} ] = data
    console.log(id, name, city, second)


Original response:

Below is the procedure for Nested object and array destructuring:

// Input data
const that = {
  state: {
    weather: {
      city: {
        name: "new york",
        country: "usa",
        sunrise: "6 AM",
        sunset: "7 PM",
        timezone: "-4"
      },
      list: [{
        main: {
          temp: 10,
          feels_like: 14
        }
      }]
    }
  }
};

// Nested Destructuring
const {
  city: {
    name,
    country,
    sunrise,
    sunset,
    timezone
  },
  list: [{
    main: {
      temp,
      feels_like
    }
  }, second]
} = that.state.weather;

// Results
console.log(name, country, sunrise, sunset, timezone);
console.log(temp, feels_like);

With default values to prevent errors - "can not read property of undefined":

// Input data
const that = {
  state: {}
};

// Nested Destructuring
const {
  city: {
    name,
    country,
    sunrise,
    sunset,
    timezone
  } = {},
  list: [{
    main: {
      temp,
      feels_like
    } = {}
  } = {}, second] = []
} = that.state.weather ?? {};

// Results
console.log(name, country, sunrise, sunset, timezone);
console.log(temp, feels_like);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I follow to generate a table using Ajax and Javascript when a button is clicked?

After spending hours following various tutorials and exploring previously asked questions, I am struggling to make this work. My HTML page looks like this: <!DOCTYPE html> <html> <head> <link type="text/css" rel="styleshee ...

When images in Ionic overlap with the side menu bar

Currently, I am in the process of developing an Android app using the IONIC framework. Within this project, I have created three divisions that contain images with shadows applied to them. However, I am encountering an issue where the side menu bar is over ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

What is the best way to save longitude and latitude coordinates in a database using the <input> method?

Learn how to use HTML code <html> <body> <p>Press the button below to receive your coordinates.</p> <button onclick="getLocation()">Get Coordinates</button> <p id="demo"></p> <script> var x = doc ...

Watch for event triggered after completion of input field with ng-modal

One of my challenges involves implementing a text input field that prompts users to enter their name: <input type="text" ng-modal="form.name" placeholder="Enter NAME"> I've also set up a watch function to monitor changes in the form's nam ...

Updating AngularJS ng-repeat when changes are made to LocalStorage with the use of store.js may not reflect immediately

One of the functionalities I want to implement is displaying a list of items (subject names) that are stored in a LocalStorage element. The code snippet in my view is structured as follows: <div class="list"> <a class="item" href="#" ng-repeat= ...

Creating a visual representation on a canvas using JQuery

$.fn.colorPicker = function () { const $div = this; const $colorPickerIcon = $("<img></img"); const $canvas = $("<canvas></canvas>").addClass("canvas"); const $context = $canvas.getContext("2d"); const $closeButton ...

The dynamically generated button is visible only once

I'm currently working on creating a status update box similar to Facebook using Javascript/jQuery. However, I've run into an issue where the button I've appended inside the div element only appears once after clicking the post button. Below ...

No results displayed for organized and queried array

As I review the material covered in my first semester of programming, I am preparing for the final exam by working on sample programs that incorporate all the concepts I have learned so far. The program outlined below is designed to read names from a file, ...

The logout confirmation message functionality in Laravel 8 is malfunctioning

In my Laravel project, I am attempting to implement a logout confirmation message that will pop up when a user clicks on the logout button. Here is the code I have added to my navbar.blade.php: <a class="dropdown-item" id="logout" hr ...

Unable to invoke parent method from child component in Vue causing issue

I am facing an issue where I am trying to trigger a method in the parent component from the child component using $emit, but for some reason, it is not working as expected. Can someone please help me troubleshoot this problem? Parent Component <templat ...

Error message "Property 'name' does not exist on type '{}'" is encountered when using Ionic/Angular HttpClient and no data type is specified

While working on my Ionic project, I encountered an error in Angular when trying to fetch data from an API using HttpClient. The error message that popped up was 'Property 'name' does not exist on type '{}'.'. Below is the cod ...

I am currently facing a challenge in React Highcharts where I am unable to remove and redraw the graph easily

Having an issue where I can't remove and redraw the chart in my React Highchart project. I've been unable to find a solution for this problem. Here is the code snippet: import { useState, useEffect, useRef } from "react"; import Highch ...

Can a webpage be redirected to another page while passing along the id from the original page?

https://i.sstatic.net/3LhYJ.png I have a page that displays shop names and addresses along with an edit function in views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoL ...

Guide to aligning the orientation of an object with a given normal vector using three.js

Imagine I have a car object where the z-rotation is positioned to face the direction it's moving in. This car is situated on an inclined ground represented by a normalized normal vector (nx, ny, nz). How can I rotate the car's x and y axes so th ...

The function goes beyond just marking individual Todos as done, as it has the capability to mark all Todos as completed

As a beginner, I am facing an issue where all the items in my to-do list are marked as done when I try to mark just one. Can someone please help me understand what I am doing wrong? I have a function called handleDoneTask that is meant to mark each indivi ...

Does JavaScript array filtering and mapping result in a comma between each entry in the array?

The code snippet above showcases a function that retrieves data from a JSON array and appends it onto a webpage inside table elements. //define a function to fetch process status and set icon URL function setServerProcessesServer1761() { var url = "Serv ...

Efficient Routing with React Router 4: Embracing Code Splitting and Component Remount

Here is the code snippet in question: import React from 'react' import Loadable from 'react-loadable' import { Route } from 'react-router-dom' class App extends React.Component { state = { kappa: false } ...

Switching between sockets on a rotational basis

Imagine there is a division in the HTML file, and an interesting game is being played where each player has the opportunity to change the color. However, there’s a twist – they can only switch colors after the other player has taken their turn. The pla ...

New update in Next.js version 13.4 brings a modification to routing system

I'm currently working with Next.js 13.4 and an app directory. I'm trying to implement a centrally located loader that will show whenever there is a route change anywhere within the app. Since routes/navigation don't have event listeners, I&a ...