Guide on organizing the Object into a precise structure in Angular

I am looking to transform the current API response object into a more structured format.

Current Output


let temp = [
    {
      "imagePath": "",
      "imageDescription": [
        {
          "language": "en",
          "text": "Today's News Updated"
        }
      ]
    },
    {
      "imagePath": "",
      "imageDescription": [
        {
          "language": "en",
          "text": "test"
        }
      ]
    },
    {
      "imagePath": "",
      "imageDescription": [
        {
          "language": "de",
          "text": "test"
        }
      ]
    },  
  ]

Desired output

let temp = {
"imagesList": {
    "en": [{
       "imagePath": "",
       "text": "Today's News Updated"
     },
     {
       "imagePath": "",
       "text": "test"
     }],
     "de": [{
       "imagePath": "",
       "text": "test"
     }]
   }
}

How can I achieve this in angular using typescript to display it in the view?

Please refer to the Sandbox Link below: Sandbox Link

Answer №1

Playground Link

interface InputImage {
    imagePath: string;
    imageDescription: InputDescription[];
}

type Language = "en" | "de";

interface InputDescription {
    language: Language;
    text: string;
}

let temp: InputImage[] = [
    {
        "imagePath": "",
        "imageDescription": [
            {
                "language": "en",
                "text": "Today's News Updated"
            }
        ]
    },
    {
        "imagePath": "",
        "imageDescription": [
            {
                "language": "en",
                "text": "test"
            }
        ]
    },
    {
        "imagePath": "",
        "imageDescription": [
            {
                "language": "de",
                "text": "test"
            }
        ]
    },
]

interface ImageWithDescription {
    imagePath: string,
    text: string,
}

interface Result {
    imagesList: {
        [key in Language]?: ImageWithDescription[];
    }
}

const result = temp.reduce<Result>((acc, val) => {
    const { imagesList } = acc;
    const { imagePath, imageDescription } = val;
    for (const { language, text } of imageDescription) {
        if (!(language in imagesList)) {
            imagesList[language] = [{ imagePath, text }];
            continue;
        }
        
        (imagesList[language] as ImageWithDescription[]).push({
            imagePath,
            text
        })
    }

    return acc;
}, { imagesList: {} });

console.log(result);

Answer №2

Here is my simplistic solution to the problem at hand:

import { OnInit } from '@angular/core';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({ .. })
export class FoobarComponent implements OnInit {
  constructor() {
  }

  ngOnInit() {
    // Assuming data is fetched using httpClient
    this.data$ = of([
      {
        imagePath: '',
        imageDescription: [
          {
            language: 'en',
            text: 'Today\'s News Updated'
          }
        ]
      },
      {
        imagePath: '',
        imageDescription: [
          {
            language: 'en',
            text: 'test'
          }
        ]
      },
      {
        imagePath: '',
        imageDescription: [
          {
            language: 'de',
            text: 'test'
          }
        ]
      }
    ]).pipe(map((data) => {
      const enList = [];
      const deList = [];
      data.forEach((item) => {
        item.imageDescription.forEach((description) => {
          if (description.language === 'de') {
            deList.push({imagePath: item.imagePath, text: description.text});
          }
          if (description.language === 'en') {
            enList.push({imagePath: item.imagePath, text: description.text});
          }
        });
      });
        return {
          imagesList: {
            en: enList,
            de: deList,
          }
        };
      }
    ));
  }
}

There are areas for optimization to enhance performance and flexibility. Nonetheless, this should serve as a good starting point.

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

Angular 2: Issue with data table not updating after item deletion

I need assistance with updating a data table after deleting an item. The database is updated correctly when I delete an item, but the table does not automatically refresh to reflect the changes. managenews.component.ts import { Component, OnInit } from ...

What are the steps for utilizing the useReducer Hook with TypeScript?

I have successfully converted a React app to Typescript, but I am facing an issue with the useReducer Hook. The error message I'm getting is preventing me from moving forward. I have attempted different approaches to passing TypeScript interfaces in ...

Exploring the complexities of cyclic dependencies and deserialization in Angular

I have encountered an issue with deserializing JSON objects in my Angular project. After receiving data through httpClient, I realized that I need to deserialize it properly in order to work with it effectively. I came across a valuable resource on Stack O ...

Angular: ViewContainer is failing to correctly insert the component next to the anchor element, instead it is placing the component inside the anchor element

I have successfully implemented a tab view with the following structure: <tabs> <ul #getVCRefHERE > <li>tab1</li> <li>tab2</li> </ul> <tab> <ng ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

The argument type provided for returning an object in Rxjs switchmap is not valid

I have created a service in Angular that fetches data from different services and combines it with the initial service's data. If the initial service returns empty data, there is no need to call the second service. Here is the code: searchData(): Obs ...

Display captions on react-player videos using an .srt file

Currently, I am working on a React/Typescript project with Next.js. A key feature of this project is a modal that utilizes 'react-player' to display videos. While the video and modal are functioning as intended, I am looking to incorporate capti ...

Issue with TypeScript while trying to define a property of a named function expression using 'let' instead of 'const'

As I continued my journey through the TypeScript handbook, I stumbled upon an intriguing concept while learning about Call Signatures. The code snippet provided in the handbook goes like this: type DescribableFunction = { description: string; (someArg: n ...

Using NestJS to inject a Factory provider into another Factory

I've gone through various questions here, but none of them addressed my issue: NestJS - Inject factory provider into another provider doesn't work I'm trying to set up an async provider that retrieves configurations from a remote repositor ...

Angular Error: Unable to access property 'users' on a null value

I am working on a component that takes in data through the @Input() decorator regarding a group. My objective is to generate a new array of objects during the initialization of the component based on the data from the group array. Below is the TypeScript c ...

Injecting Basic Data Types into Your Angular 2 Service

I am facing an issue with a basic service that requires a single string parameter. import {Injectable} from 'angular2/core'; @Injectable() export class MyService { constructor(someValue: string) { } } When I remove the string param fro ...

Deliver a numerical input to the component on an equivalent hierarchical tier

I need to find a way to pass the values of the "things" array to another component on the same level in my app. The structure of my app is as follows: sidebar.component data.service body.component In the sidebar component, I have a button that triggers a ...

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...

How can TypeScript limit the number of properties allowed to be passed as a function parameter?

Here is what I currently have: export interface RegionNode { nodeSelected: boolean; nodeEditable: boolean; zone: Partial<Zone>; parent: RegionNode | null; children: RegionNode[]; } Now, I am looking for a sleek solution to create ...

retrieve a nested object's property using a dynamic string

Here is the object model I am working with: export class FrcCapacity { constructor( public id?: number, public frcId?: number, public capGroupId?: number, public capGroup?: CapGroup, public salesProductId?: number, public p1?: num ...

After defining the NEXTAUTH_URL and NEXTAUTH_SECRET variables, the getServerSession(authOptions) function in NextJS is returning null

I've been attempting to set up OAuth with the Google provider for my Next.js 13 web application. Unfortunately, I'm encountering an issue where getServerSession(authOptions) is returning null. Despite trying various solutions such as setting NEXT ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

When utilizing JavaScript syntax and performing API testing with Postman

Hello, I need some assistance from experts in connecting to Postman using the JavaScript code provided below. When running nodemon, the connection appears to be normal with no errors. Also, the GET request sent to Postman works fine. However, I am encounte ...

Issues with Angular's Material UI CDK Virtual Scroll Viewport functionality not functioning as intended

While following the official documentation here to set up a virtual viewport, an error message appeared in the HTML component: Error message 'cdk-virtual-scroll-viewport' is not a recognized element: 1. If 'cdk-virtual-scroll-viewport' ...

Can you explain why it prints to the console twice every time I try to add an item?

This is a note-taking application created using Angular and Firebase. The primary functionalities include adding items and displaying them. I noticed a strange behavior where my ngOnInit() method is being called twice every time I add an item. As shown in ...