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

TypedScript: A comprehensive guide to safely omitting deep object paths

Hi there, I have a complex question that I would like some help with. I've created a recursive Omit type in TypeScript. It takes a type T and a tuple of strings (referred to as a 'path'), then removes the last item on the path and returns t ...

Exploring the Capabilities of TypeScript 1.8 in Visual Studio 2017

Recently, I've encountered an issue with my Visual Studio project that was created using TypeScript 1.8 in Visual Studio 2015. Upon upgrading to Visual Studio 2017 and attempting to open the project in the new IDE, I noticed that the TypeScript versio ...

Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below: import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add ...

Utilizing the `in` operator for type narrowing is yielding unexpected results

Attempting to narrow down a type in TypeScript: const result = await fetch('example.com') if (typeof result === "object" && "errors" in result) { console.error(result.errors); } To clarify, the type of result before the if condition should be ...

Setting the current date in Angular using TypeScript and storing it in a MySQL database

As I delve into learning Angular, I am focused on practicing with a form. Specifically, I am attempting to include the current date when inputting client records along with their RFC, branch, and cost. Unfortunately, my attempts have been unsuccessful in i ...

The comparison between using Reflect.decorate and manual decorating in TypeScript

Here are two different decorators that I am using: import "reflect-metadata"; const enum MetadataTypes { Type = "design:type", Paramtypes = "design:paramtypes", ReturnType = "design:returntype" } function DecoratorA(target: any, key: string): void ...

Component that can be used multiple times to load data

I am currently working on a react/nextjs/redux application where each component needs to call a different backend API. The main challenge I am facing is the lack of reusability in loading data components due to some repetitive code that I would like to el ...

Encountering the "Unrecognized teardown 1" error when subscribing to an Observable in Typescript and Angular2

Having trouble with using an Observable in my Angular2.rc.4 Typescript app. Check out the plunker for it here: https://embed.plnkr.co/UjcdCmN6hSkdKt27ezyI/ The issue revolves around a service that contains this code: private messageSender : Observable< ...

Following the recent update to webpack-dev-server and webpack, certain modules are being requested that do not exist in the project

Recently, I made updates to my project that involved Vue.js and Typescript. After updating webpack and webpack-dev-server, I encountered a problem where certain modules were missing when attempting to run the project in development mode. Here is some addi ...

Error in Template Syntax for External Pug Templates: Component template must have a root element, not just plain text

I've been struggling to make Pug templates work with Vue class-based components using a separate file for the pug template. The documentation suggests that adding this code should do the trick: // webpack.config.js -> module.rules { test: /&bsol ...

"Take control of FileUpload in PrimeNG by manually invoking it

Is there a way to customize the file upload process using a separate button instead of the component's default Upload button? If so, how can I achieve this in my code? Here is an example of what I've attempted: <button pButton type="button" ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Getting a multidimensional array from JSON in Typescript: A step-by-step guide

Below is a sample of a JSON array containing information about cars. var cars = { "cars": { "john": [], "alex": [ "ford" ], "hilton": [], "martin ...

Is it feasible to incorporate a multi-level navigation menu into the "NavItem" component using MaterialUI with TypeScript?

Instructions for creating a multi-level navigation menu using MaterialUI and TypeScript: To the existing '/questions' section, it is desired to include the following 2 navigation menus: /questions/Tags /questions/Users This should resemble the ...

The issue with functions not executing when triggered by HammerJS

In my application, there is a component that displays information for different days as they are cycled through using the functions dayUp() and dayDown(). Here is an example of how these functions are structured: dayUp() { if (this.dayCount == 7) { ...

Tips for selecting an image from the gallery with IONIC 3

Looking for guidance on extracting an image from the gallery in IONIC 3? I attempted to grab an image from the gallery but encountered some issues. Visit this link for more information This resource may also be helpful ...

Encountering an error with the Typescript 'any' type in Ionic 2

I need help understanding an error I encountered: EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in build/pages/search/search.html:17:14 ORIGINAL EXCEPTION: Cannot find a differ supporting object 'function () { return [ { ...

Guide to incorporating Bootstrap icons into an Angular application through programming techniques

Have you checked out the official bootstrap documentation for information on how to use their icons? https://i.stack.imgur.com/N4z2R.png I'm currently trying to understand the package and its usage. However, none of the options in the documentation ...

Reactive form loses preloaded data due to ExpressionChangedAfterItHasBeenCheckedError when modal is dismissed

Within my project, I have a sidenav that contains various links. One of these links directs to a component that presents some input data. Below is the TypeScript code: @Input() data: MyData; myModal: BsModalRef; editForm: FormGroup; ngOnInit(){ this. ...

`How can TypeScript be used to designate the type of a variable within the useState hook?`

I defined a variable called 'text' and a hook named 'setText'. I'm using them to update the value of a form input field. How can I ensure that 'text' is always of type string? This is what I attempted: interface TextInt ...