Angular2: Adding a new array to all objects within an existing array

I am working with a REST API that delivers data in JSON format. I have stored this data in an array of objects, but now I want to add a new empty array to each object which is proving to be challenging. Below is a snippet of how my REST API data is structured, and I have indicated where I would like to insert the new array in the comments.

       content = [
          {
            text: 'abc',
            options: [
                {
                  Id: 1,
                  Text: 'aaa'
                },
                {
                  Id: 2,
                  Text: 'bbb'
                },
                {
                  Id: 3,
                  Text: 'ccc'
                }],
// ARRAY[]

    },
          {
            text: 'def',
            options: [
                {
                  Id: 21,
                  Text: 'qwerty'
                },
                {
                  Id: 22,
                  Text: 'zxcv'
                },
                {
                  Id: 23,
                  Text: 'asdf'
                }],
    // ARRAY[]
          }
      }]

This is what I have attempted so far.

public newarr:Array<any>;
this.httpservice.post('RESTUrl').subscribe(resp=>{
     this.contents = resp.data;
     this.contents.forEach((x:any)=>{
       x.push(this.newarr);
     });
     console.log("contents",this.contents);
      });

Answer №1

Simply add using dot notation, all you have to do is this:

this.someService.get('APIUrl').subscribe(response=>{
   this.data = response.data;
   this.data.forEach((item:any)=>{
     item.<property_name> = this.newArray;
   });
   console.log("data",this.data);
});

By doing this, your variable will be appended to the existing Array.

Answer №2

Seems like there is an attempt to add an array to an object incorrectly, the correct syntax should be x.NewArray = this.newarr or a similar approach.

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

Is there a way for me to pass the templateUrl data from the parent component to another component

Currently, I am in the process of learning Angular2 and facing a situation where I have a dropdown that appears on multiple pages. Each time it is called, the contents of the dropdown change, but the structure remains the same. This is why I have set it up ...

CORS policy has blocked Angular7 because the requested resource does not have the necessary 'Access-Control-Allow-Origin' header

While attempting to access the URL: http://localhost:8080/hello-world/path-variable from Angular to Spring Boot, everything was functioning correctly until I integrated Spring Security. I implemented basic authentication security in Spring Boot, requiring ...

Having trouble dismissing Bootstrap alerts in TypeScript?

There seems to be an issue with the close button in a simple piece of code. The alert is displayed correctly, but clicking on the close button doesn't close the alert. Currently, I am using bootstrap 5.2.3. My code consists of a basic main file and an ...

The module '@angular/core/core' does not contain the exported member 'ɵɵFactoryDeclaration'

Hello everyone, We are currently experiencing an issue with our Angular project during the ng build process. An error message is popping up that has us stumped. Despite trying various solutions provided by the GitHub and Stack Overflow communities, we stil ...

Conceal components using routing in Angular2 release candidate 1

I have a request regarding certain elements that are to be displayed on all pages except the login page. I am considering using either ngIf or the hidden property of the elements to hide them when the user is on the login page. Here is what I have attempt ...

Using Angular2 to assign the response from an http.get request to a class object

I am a beginner in Angular and I have a JSON file that holds the configuration URL for my application. Path: app/config/development.json { "apiUrl": "http://staging.domain.com:9000/", "debugging": true } Below is the content of my config.service.t ...

Create a custom navigation system for ng-bootstrap tabset using manual controls

Currently, when I click on the "Client" tab, the content opens. Similarly, when I click on the "Rate card" tab, the rate card content opens. However, the navigation does not work when I use the arrows at the bottom. How can I enable navigation for the ar ...

The error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...

Creating components on the fly as soon as their resources become available

I need to dynamically add a child component within another component only after the image inside the child component has been fully loaded. child.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'a ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

Requesting Next Page via Angular GET Method for Paginated API

Having trouble loading data from a paginated REST API using the code below. Any suggestions for a better approach are welcome! component.ts import { Component, OnInit } from '@angular/core'; import {HttpClient} from '@angular/common/http&a ...

Managing non-mandatory information in a structured domain representation: What's the best approach?

When working on applications or domain models, I often ponder the most effective approach to handling incomplete or optional data. Typed languages like TypeScript and C# offer the advantage of defining models with strict types. While this can be beneficial ...

It's possible that the "device.interfaces" variable has not been defined

I am currently working on creating a USB driver in TypeScript using the libusb library to adjust my keyboard lighting. However, I encountered an issue where I received a 'possibly undefined' error when trying to retrieve the interface number. The ...

TypeScript creates a .d.ts file that contains declaration statements rather than export declarations

When compiling my code using the command tsc --p typescript/tsconfig.json --outFile "dist/umd/index.d.ts", I encountered an issue. The contents of my tsconfig.json file are as follows: { "include": ["../src/**/*"], "exclude": ["../**/*.test.ts"], ...

The content within the mat-card-content paragraph exceeds the boundaries of the mat-card container,

I recently began working with Angular Material and came across an issue. When I have a shorter text paragraph, it overflows the card. However, when I use a larger paragraph, the text wraps nicely. Here is the code snippet: <mat-card *ngFor="let s ...

What is the proper method for specifying the path to my index.tsx file within a React application?

After using npx create-react-app my-app --template typescript to generate my React app, I decided to reorganize the files by moving them to /src/client and relocating my Express backend to /src/server. However, upon running the relocated React app, I encou ...

Transforming the Server-side model to the Client-side model within Angular 4

My Server-side C# model public class Instructor:Entity { public string Name { get; set; } public string PhoneNo { get; set; } } Client-side TypeScript model export class Instructor extends Entity { public name:string; public address ...

Creating one-to-one relationships in sequelize-typescript can be achieved by setting up multiple foreign keys

I have a question about adding multiple foreign keys to an object. Specifically, I have a scenario with Complaints that involve 2 Transports. One is used to track goods being sent back, and the other is used for goods being resent to the customer. @Table({ ...

Troubleshooting problems encountered in Nest.js due to modifications made within a service.ts file

I'm currently working on a Nest.js project and here is the content of the automobile.service.ts file: import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Car } from './enti ...