How to display a nested array in TypeScript following a specific structure

Can anyone assist with printing the variable below in the specified format?

Data

export const shop_items: Inventory:{
    Toys{
        Balls: {
            BallId: 001uy,
            BallName: Soccerball,
            SignedBy: David_Beckham,
        },
    },
    Books:{
        Novel: {
            BookId: ‘001fd’,
            BookName: ‘Beauty and the beast’,  
        },
        Puzzle: {
            BookId: ‘002sz’,
            BookName: ‘Sherlock Holmes’,  
        },
        Sci-fi: {
            BookId: ’003tr’,
            BookName: ‘Dr.Gadget’,  
        },
    }
}

Format

The toy variables are to be printed as is, while the data under Books should be displayed in a specific path format.

BallId : 001uy
BallName : Soccerball
SignedBy : David_Beckham

/Books/Novel/BookId : 001fd
/Books/Puzzle/BookId : 002sz
/Books/Sci-fi/BookId : 003tr

Answer №1

This is the solution to your issue. Give it a try on the Playground.

type Ball = { BallId: string; BallName: string; SignedBy?: string };
type Book = { BookId: string; BookName: string; SignedBy? : string}

type Inventory = { Books: { [Item: string]:  Book} } & { Toys: { [Item: string]:  Ball } };
const shop_items: Inventory = {
  Toys: {
    Balls: {
      BallId: "001uy",
      BallName: "Soccerball",
      SignedBy: "David_Beckham",
    },
  },
  Books: {
    Novel: {
      BookId: "001fd",
      BookName: "Beauty and the beast",
    },
    Puzzle: {
      BookId: "002sz",
      BookName: "Sherlock Holmes",
    },
    "Sci-fi": {
      BookId: "003tr",
      BookName: "Dr.Gadget",
    },
  },
};

function printBook(name: string, book: Book){
    console.log(`Book/${name}/bookId: ${book.BookId}`);
}

function printBall( ball: Ball){
    console.log(`BallId: ${ball.BallId}`);
    console.log(`BallName: ${ball.BallName}`);
    console.log(`SingnedBy: ${ball.SignedBy}`);

}
Object.entries(shop_items.Toys).forEach((val: [string, Ball]) => printBall(val[1] ))
Object.entries(shop_items.Books).forEach((val: [string, Book]) => printBook(val[0],val[1] )

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

React Query successfully retrieves the path, but unfortunately fails to render the image in the display

Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet: export const useGetProductImagesByProductId = (productId: string) => useQuery({ queryKey: ['productIm ...

Tips on using Visual Studio Code to troubleshoot Angular 4 unit tests

I am working on an Angular 4 project with Material design in Visual Studio Code. The setup is done using angular/cli. Currently, I have been writing unit tests using Karma and Jasmine. However, when trying to debug the tests by setting breakpoints, it doe ...

Exploring the Issue with SWR Hook in Next.js using TypeScript

Seeking assistance with the SWR hook as I navigate through some challenges while attempting to use it effectively. This time, the issue appears to be minor. The objective is to set a breakpoint in my API to retrieve data, using axios. The problem arises ...

Discuss the communication paths between Server and Client components in the upcoming 14 days

Currently, my objective is to transfer state from a client component to a server component, perform some actions on the server, and then send the updated state back to the client through props. I am in the process of building a booking system using tools ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

"Retrieving an element from an array may result in a value of

While going through an array of objects in my Angular component class, I faced a strange issue where the properties kept showing up as undefined. The function responsible for this behavior looks like this: upload(): void { const { fileHandles, related ...

Organize by a collection of strings or a collection of enums

Here is a list of objects that I have: enum MealType { Breakfast, Lunch, Dinner } interface FoodItem { name: string, type: MealType[], } const foodItems: FoodItem[] = [ { name: 'Pizza', type: [MealType.Lunch, MealType.Dinner ...

Adding a class to a child component layout from a parent component in Angular 12 and Typescript can be achieved by using the ViewChild decorator

Incorporating the child component into the parent component is an important step in the structure of my project. The dashboard component serves as the child element, while the preview component acts as the parent. Within the parent (preview) component.htm ...

Setting an expiry date for Firestore documents

Is it feasible to set a future date and time in a firestore document and trigger a function when that deadline is reached? Let's say, today I create a document and specify a date for the published field to be set to false fifteen days later. Can this ...

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

A guide on simulating childprocess.exec in TypeScript

export function executeCommandPromise(file: string, command: string) { return new Promise((resolve, reject) => { exec(command, { cwd: `${file}` }, (error: ExecException | null, stdout: string, stderr: string) => { if (error) { con ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...

TypeScript error: Attempting to utilize an argument of type 'any[]' that cannot be assigned to a parameter of type 'SetStateAction<never[]>'

In my React app built with TypeScript, there is a specific section where I need to merge a predefined set of default users with negative userIds and other users fetched using the getUsers(orgId) API. Here's the code snippet: .... const [assigned ...

What is the best way to determine the type of a key within an array of objects

Suppose I have the following code snippet: type PageInfo = { title: string key: string } const PAGES: PageInfo[] = [ { key: 'trip_itinerary', title: "Trip Itinerary", }, { key: 'trip_det ...

Is ts-node necessary for using TypeScript in Node.js?

Having trouble setting up a Node.js application in Visual Studio Code using TypeScript due to issues with importing modules. Initially, I created an index.ts file with the import statement -> import config from './app/config.json'; This resu ...

Triggering a class in Angular when another class is activated through JavaScript

My goal is to apply the class "xyz" when the class "xy" is activated using ngClass. I am looking to achieve the following scenario: If the class "xyz" is present in the tag, then activate the class "xy" Using ngClass="'xyz', 'xy'" ...

Sometimes the downloaded xlsx file may become corrupted

Currently, I am working on developing a project using Angular4 with Typescript. One of the tasks involved creating a blob utilizing the XLSX-populate library. Below is an example showing the code snippet for generating a valid xlsx object: var url = wind ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...