Mapping with Angular involves iterating over each element in an array and applying a function to each one

I am working with an API that provides data in a specific format:

{"data": [

{ path: "some path", site_link: "link", features: ['feature1', 'feature2'] }

... ]}

Now, I have a service called getSites()

getSites(): Observable<Site[]> {
    return this.http.get<Site[]>(this.API_URL).pipe(
      map((site: SiteResponse): Site[] => {
        return site.data.map(e => new Site().deserialize(e));
      })
    );
  }

This is the Site response interface

export interface SiteResponse {
  data: {
    path: string,
    siteLink: string,
    features: string[],
  }[];
}

Let's take a look at the Site model

export class Site implements Deserializable {
  path: string;
  siteLink: string;
  features: Feature[];

  deserialize(input: any): this {
    Object.assign(this, input);
    console.log('----input', input);
    console.log('----this', this);
    console.log('----features', input.features);
    this.features = input.features.map(feature => new Feature().deserialize(feature));
    return this;
  }
}

Next, we have the Feature model

export class Feature implements Deserializable {
  feature: string;

  deserialize(input: any): this {
    Object.assign(this, input);
    return this;
  }
}

Here is what I am receiving https://i.sstatic.net/sAwTA.png

I am facing an issue where the features content is splitting instead of creating objects for each value in the array.

The functionality works well on the first level of the array as it correctly creates an instance of Site.

Answer №1

The SiteResponse's features property references an array of strings, meaning it does not have a feature property. When deserializing the Feature model, the deserialize method attempts to assign a string value to object properties. See example below.

export class Feature implements Deserializable {
  feature: string;

  deserialize(input: any): this {
    this.feature = input;
    return this;
  }
}

Answer №2

The string was successfully converted into an array-like object after removing the deserialization process, resolving the issue.

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

Can you explain the distinction between these codes?

function Example() { this.display1 = function() { alert(1) } } Example.prototype.display2 = function() { alert(2) } var e = new Example e.display1() e.display2() display1 and display2 both have the ability to trigger an alert showing a number. Do yo ...

My page is experiencing delays due to setInterval

Currently, I am delving into the world of Chrome Extension development and am faced with a roadblock in replacing elements on a live chat page. While most of my tasks are running smoothly, the one thing causing issues is the setInterval option that trigger ...

Trouble with displaying and hiding elements using multiple Javascript functions

I'm encountering an issue with a JavaScript function - when I implement the first paragraph on its own, it works as expected. However, when I introduce and execute the second paragraph, the show and hide function for "ABOUT THE PROJECT" toggles the te ...

Creating an HTML table using an array of objects

I'm currently working on creating a function that will generate an HTML table from an array of objects. The array provided below is what I need to convert into a table. let units = [ { 'code': 'COMP2110', &apos ...

What is the best way to retrieve an item from an array?

I have an array containing multiple records and I need to extract just one record from it using its id as an object. However, the result I'm getting is an array with that single record. Is there a way to resolve this issue? Result: [{…}] 0: {id ...

Retrieving Data from API in Angular 6/7 upon Navigating Back to Previously Visited Page

I'm currently navigating my way through angular and encountering a small hurdle. I aim to guide a user to a data entry page where most fields are pre-filled by retrieving data from the database based on a record id. The user then modifies some fields, ...

The functionality of the d3 Bar chart with a tool tip seems to be malfunctioning

Working on a D3 svg chart with built-in tooltips using the d3-tip library. Check out the original code here. Utilizing Django as the back end to populate log count per year from datetime. Successfully populated axis and labels except for the bars. Here i ...

Error encountered with underscore template - Unforeseen SyntaxError: Unexpected token <

I encountered an error when attempting to load one of my underscore templates. It seems to be related to an issue in the for loop, which I suspect should be a .each loop, but I'm still trying to grasp its structure. Here is a snippet of my template: ...

Material Style Minimal - There is a slight space between the text field and the colored line at the bottom

Having a problem with Material Design Lite text field where there is a small gap between the bottom colored line and the gray starting line. Every MDL text field example I try on my page shows the same issue. What could be causing this locally? My frontend ...

Guidelines for filling an Express handlebars template and sending it via email

I am currently utilizing node.js, express, express-handlebars, and nodemailer for my project. My objective is to populate an HBS template with content and style it as an email before sending it out. The end result can be viewed below (first rendered in the ...

Tips on how to retrieve the value of the second td in an HTML table when clicking on the first td utilizing jQuery

There is a specific requirement I have where I must retrieve the value of the second td in an HTML table when clicking on the first column. To accomplish this task, I am utilizing jQuery. $('.tbody').on('click','tr td:nth-child(1) ...

"Sorry, but it appears that the tooltip-basic module is

I have been attempting to implement ng-bootstrap tooltips (or any of their widgets) in my Angular 7 application. Despite what seems to be a successful installation of ng-bootstrap, I am facing an issue where nothing happens when I try to use the tooltip as ...

My CSS seems to be causing an issue and preventing the function from running correctly. Now I just need to

I'm currently working on a project and following a tutorial to help me create a navigation bar. The tutorial I am using can be found here: https://www.youtube.com/watch?v=gXkqy0b4M5g. So far, I have only reached the 22:05 mark in the video. I have su ...

How can you make sure that VS Code always utilizes relative paths for auto imports in TypeScript?

VS Code has been automatically importing everything using Node-like non-relative paths relative to baseUrl, which is not the desired behavior. Is there a way to instruct VS Code to import everything with relative paths, excluding Node modules? Removing t ...

What is the best approach to eliminate an element from the array cart using JavaScript?

I currently have an array: [ 0: {title: "Banana", price: 1.00, count: 2}, 1: {title: "Taco", price: 3.99, count: 1}, 2: {title: "Burrito", price: 6.50, count: 1}, 3: {title: "Soda", price: 1.25, count: 1} ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

The component has reached the maximum limit of recursive updates

I have been working on a simple fetching function and encountered a warning message: The warning states: Maximum recursive updates exceeded in component. This indicates that a reactive effect is mutating its dependencies, causing it to trigger itself recu ...

Focus on the original control that triggered a jQuery AJAX POST during a postback event

function pageLoad() { $(".VoteUp").live("click", function () { var Id = $(this).attr("index"); d = JSON.stringify({ "Id": Id }) $.ajax({ type: 'POST', url: '../API ...

What are the steps for configuring a dynamic variable?

One issue I encountered was setting up a variable in vue that updates when the screen orientation changes. Despite adding this variable to the data object, it did not become reactive as expected. This is my initial data function for the component: data() ...

What is the best way to halt a CSS transition using JavaScript when dealing with an image?

I am facing an issue while attempting to create a basic CSS transition using JavaScript. The goal is for the start button to trigger the movement of an element, based on the duration of the keyframe animation. Then, clicking the end button should make the ...