What is the process of destructuring an array containing objects?

Examining this JSON structure:

{
    "Person": {
        "UID": 78,
        "Name": "Brampage",
        "Surname": "Foo"
    },
    "Notes": [
      {
            "UID": 78,
            "DateTime": "2017-03-15T15:43:04.4072317",
            "Person": {
                "Name": "Brampage",
                "Surname": "Foo"
            },
            **"Note":** {
                "Title": "Lorem Ipsum...",
                "Content": "Blaat blaat blaat blaat ..."
            }
       },
       {
            "UID": 78,
            "DateTime": "2017-03-15T15:43:04.4072317",
            "Person": {
                "Name": "Brampage",
                "Surname": "Foo"
            },
            "Note": {
                "Title": "Lorem Ipsum...",
                "Content": "Blaat blaat blaat blaat ..."
            }
        }
        // other entries...
    ]
}

How do I deconstruct this object to extract these specific components: Person, Notes.Note[].

This is my attempted solution, which unfortunately does not yield the desired outcome:

this.http.get(url)
.map(res => {
    const jsonObject = res.json();

    // Destructuring
    const { Person} = jsonObject;
    const [{ Note }] = jsonObject.Notes;

    return {
        person: Person,
        note:[
            Note
        ]
    }
})
.subscribe(
    usefullInformation => {
        console.log(usefullInformation);
    },
    error => {
    }
);

Referencing TypeScript's documentation for guidance on destructuring: TypeScript Destructuring Documenation

Answer №1

According to Ryan, manual serialization of your data is necessary because destructuring does not handle conditional statements. To address this issue, it is recommended to create a serializer function that can be triggered by Observable.map on the data.

Here's an example:

const info = {
    "User": {
        "ID": 22,
        "Name": "JohnDoe",
        "Lastname": "Smith"
    },
    "Entries": [
        {
            "ID": 22,
            "Date": "2020-09-23T08:12:34.5678901",
            "User": {
                "Name": "JohnDoe",
                "Lastname": "Smith"
            },
            "Entry": {
                "Title": "Sample Title...",
                "Content": "Lorem ipsum dolor sit amet..."
            }
        },
        {
            "UID": 22,
            "DateTime": "2020-09-23T08:12:34.5678901",
            "Person": {
                "Name": "JohnDoe",
                "Surname": "Smith"
            },
            "Note": {
                "Title": "Sample Title...",
                "Content": "Lorem ipsum dolor sit amet..."
           }
        }
    ]
}

function getEntriesByID(id, entries) {
  return entries
    .filter(item => item.ID === id)
    .map(item => item.Entry);
}

const { User } = info;
const Entries = getEntriesByID(User.ID, info.Entries);

console.log(User, Entries);

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

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Is there a possibility that typescript decorators' features will be polyfilled in browsers lacking ES5 support?

According to the typescript documentation, a warning is issued: WARNING  If your script target is lower than ES5, the Property Descriptor will be undefined. If the method decorator returns a value, it will act as the Property Descriptor for the method. ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

Best Practices for Organizing Imports in Typescript to Prevent Declaration Conflicts

When working with TypeScript, errors will be properly triggered if trying to execute the following: import * as path from "path" let path = path.join("a", "b", "c") The reason for this error is that it causes a conflict with the local declaration of &ap ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

Supabase Authentication User Interface Error: Uncaught TypeError - Unable to access properties of null (specifically 'useState')

Concern Whenever I incorporate this Auth component into my login page, I encounter an issue. I am attempting to adhere to the guidelines provided in Supabase Auth with Next.js Pages Directory. If you suspect that this problem stems from a version discrepa ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

Uncertain about the distinction between reducers and dispatchers when it comes to handling actions

I'm feeling a bit confused regarding reducers and dispatchers. While both receive actions as parameters, it doesn't necessarily mean that the actions I use in my dispatchers are the same as those used in my reducers, correct? For example, if I h ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

What is the most efficient way to remove all typed characters from fields when clicking on a different radio button? The majority of my fields share the same ngModel on a separate page

Is there a way to automatically clear all typed characters in form fields when switching between radio buttons with the same ngModel on different pages? I noticed that the characters I type in one field are retained when I switch to another radio button. ...

The TypeScript rule in the project-specific .eslintrc.js file is not being applied as expected

Currently, I am following a tutorial on Ionic/Vue 3 which can be found here. However, when I try to serve the project, I encounter the following error: https://i.stack.imgur.com/k4juO.png It appears that my project-level .eslintrc.js file is not being ap ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Excluding a common attribute from a combined type of objects can lead to issues when accessing non-common attributes (TypeScript)

In the process of developing a wrapper function, I am passing a refs property into a send function. The Event type used to construct my state machine is defined as an intersection between a base interface { refs: NodeRefs } and a union of possible event ob ...

Error message in TypeScript with Puppeteer library: "Element not found"

Incorporating puppeteer-core as a dependency in my TypeScript project within Visual Studio 2019 has caused an issue during the build process. The error message displayed is shown by a red squiggly line under Element: https://i.stack.imgur.com/HfJCu.png ...

What is the method to remove curly brackets from a different data category?

If I have a type like this type Z = {a: number} | {} | {b: boolean} | {c: string} | ...; Is there a way to get the same type but without {}? type Y = Exclude<Z, {}>; ⇧This will result in Y = never, because all variants can be assigned to {} and a ...

Navigating in express

Here is the structure I am working with: server.ts routes/ index.ts homeRoute.ts In server.ts: let app = Express(); app.use(router); In routes/index.ts: const routes = Router(); export default function router() { routes.use('/home' ...