Generating objects dynamically using Angular 2 framework

My goal is to dynamically create objects and add data using TypeScript.

For instance:

let data={
    "date":"27-5-2017",
    "name":"John"
};

This represents my initial object. Now, I aim to include additional data in it, such as subjects.

"Subject1":"20"
"Subject2":"30"

These subjects can vary from one student to another. How can I append these Subjects into the data object?

Answer №1

Here is a simple way to define it:

let item:any;

If you already have a JSON object set up: You can simply do this

item['new_key'] = newValue;

If the object is not initialized and you want to add data for the first time

item = {'new_key' : newValue };

Answer №2

One approach would be to define a class for handling student information in a structured manner. This method offers benefits such as maintaining consistent property names, unlike when adding properties dynamically using methods like data['subject1'] = 'math'; or data.subject1 = math.

class Student{

  public name: string;
  public dateOfEntry: string;
  public subjects: Array<Subject>;

  constructor(name: string, dateOfEntry: string){
    this.name = name;
    this.dateOfEntry = dateOfEntry;

    this.subjects = new Array<Subject>();
  }

  public addSubject(subject: Subject){
    // Only add the subject if it is not already in the list
    if(!this.subjects.find(val => val == subject))
      this.subjects.push(subject);
  }

}


class Subject{
    public name: string;

    constructor(name: string){
        this.name = name;
    }
}

When creating a new student instance...

let bob: Student = new Student("bob", new Date().toString());
bob.addSubject(new Subject("Math")); // Adds to the list
bob.addSubject(new Subject("English")); // Adds to the list
bob.addSubject(new Subject("Math")); // Will not add as it already exists

Answer №3

To assign values directly, use this format:

info.SubjectA = "40"
info.SubjectB = "50"

Answer №4

One way to assign a value directly is by using data.key = value.

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

Guide on how to use window.resize subscription in an Angular service?

I have been experimenting with the WindowService in my Angular project. Here is the code I have written: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; interface WindowSize { width?: number; height? ...

Creating a type-safe dictionary for custom theme styles in Base Web

In my Next.js project, I decided to use the Base Web UI component framework. To customize the colors, I extended the Theme object following the guidelines provided at . Interestingly, the documentation refers to the theme type as ThemeT, but in practice, i ...

Error: Disappearing textarea textContent in HTML/TS occurs when creating a new textarea or clicking a button

I've encountered an issue with my HTML page that consists of several textareas. I have a function in place to dynamically add additional textareas using document.getElementById("textAreas").innerHTML += '<textarea class="textArea"></text ...

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...

What are the best practices for utilizing an array of routes?

I'm new to working with react but I noticed something strange. My routes are currently set up like this: <Main> <Route exact path="/home" component={Home} /> <Route exact path="/home1" com ...

React Native Async Storage: displaying a blank page issue

I am facing an issue while attempting to save my data locally using AsyncStorage, specifically with the getData method. const storeData = async (value: string) => { //storing data to local storage of the device try { await AsyncStorage.setItem(& ...

What is the best way to invoke a function in a React component from another component?

I am working with a component structure that includes the Input component. In this component, there is a function called validate that is triggered by the onChange event. Here is a snippet of the code: https://i.sstatic.net/WjCLy.png import React, {FC, us ...

Can I utilize a specific interface type within another interface?

Can I pass an object along with its interface to a React component? Here's a sample of the interface I'd like to incorporate: interface TableProps { ObjectProps: Interface (not functioning properly); objects: Array<ObjectProps>; } Is i ...

React waitforelement fails to work in conjunction with asynchronous calls

I am currently experimenting with a straightforward login form that includes an asynchronous call in React using TypeScript and classes. Here is how my component appears: import * as React from 'react'; import { LoginService } from './servic ...

Restoring previous configuration in Ionic2 from the resume() lifecycle method

Encountering an issue with my ionic2 application where I save the last state in local storage when the app goes to the background. Upon resuming, it checks for the value of lastState in local storage and pushes that state if a value exists. The specific er ...

Passing data through multiple levels in Angular

Imagine you have a main component called A with a variable x inside it that you want to pass to a child component B. Using the @Input annotation makes this task simple. But what if component B has its own child component C? How can we successfully pass t ...

What are the steps to implement Owl Carousel 2 in Angular2?

Struggling to integrate Owl Carousel 2 into my Angular2 project, I have hit a roadblock. Could someone kindly provide a detailed walkthrough on how to effectively configure it? ...

Typescript encounters transpilation issues when the spread operator is omitted for undefined values {...undefined}

I am currently working on a TypeScript project where I have encountered a peculiar issue. Within some of my TypeScript files, I am including a plain JavaScript/Node file named config.js. The content of config.js is as follows: 'use strict'; modu ...

Understanding the Union Type in Typescript and Its Application in Angular Development

I came across this piece of code: interface Course { code: string; name: string; user: number | { id: number; name: string; }; } This indicates that a course object can contain either the user object or the user key. When fetching the cour ...

Displaying updated information in Angular

I recently developed a chat application using Angular that utilizes the stomp socket from @stomp/ng2-stompjs. To display all messages, I am leveraging *ngFor. <p *ngFor="let item of messages" style="padding: 5px; font-size: 18px"> <span style ...

Changing the state object without using the setState function, but rather utilizing an object method

Utilizing a class within my "useState" hook, with a method to alter its content, here's a concise example: class Example { bar: string; constructor() { this.bar = 'bar'; } changeBar() { this.bar = 'baz ...

Angular4-carousel fails to display content

I have been trying to integrate the angular4-carousel into my angular 4 application. Although I am not receiving any errors, the carousel is not displaying as expected. In my app.component.html file, I have included the following code: <carousel [sour ...

Adding a # before each routing path: A step-by-step guide

One key difference between Angular 1 and Angular 4 is that in Angular 1, the routing path always includes a "#" symbol, whereas in Angular 4, it does not. I believe there may be a way to configure this function based on what I observed in the ng-bootstrap ...

Firebase initialization unsuccessful due to incorrect directory placement

I've been encountering an issue while deploying my Angular 2 project to Firebase. The initial deployment was successful, but subsequent attempts only show the Firebase Hosting welcome page instead of my project in the URL. I've realized that even ...

Implement feature to toggle function upon clicking radio buttons using bootstrap and angular 5

Currently, I am utilizing Angular 6 and Bootstrap 4. Within my project, there exists a Bootstrap button group: <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary"> <input type="radio" ...