Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents constructor using a json object.

export default class CustomerEvent {
    constructor(customer_event: any) {
        this.event_title = customer_event.event_title;
        this.customer = customer_event.customer;
        this.total_budget = customer_event.total_budget;
        this.no_of_people = customer_event.no_of_people;
        // How can I initiate array of EventDate objects and assign to this.dates?
        this.dates = /**array of new EventDate(customer_event.dates) **/;
    }
    event_title: string;
    customer: Customer;
    total_budget: number;
    no_of_people: number;
    dates: EventDate[];

}

class EventDate {
    constructor(date: any) {
        this.start_date = date.start_date;
        this.end_date = date.end_date;
    }
    start_date: Date;
    end_date: Date;
}

If anyone could provide guidance on this matter, it would be greatly appreciated. Thank you!

Answer №1

To create a new empty array, simply do the following:

constructor(new_customer_event: any) {
  this.event_title = new_customer_event.event_title;
  this.customer = new_customer_event.customer;
  this.total_budget = new_customer_event.total_budget;
  this.no_of_people = new_customer_event.no_of_people;
  this.dates = [];
}

If you want to convert an incoming array, use the following method:

...
this.dates = new_customer_event.dates.map(date => new EventDate(date));
...

Answer №2

The Angular Style Guide emphasizes the use of interfaces for defining data models over classes:

It is recommended to utilize interfaces for data models.

So, when modifying your code, consider structuring it like this:

export interface EventDate {
  start_date: Date;
  end_date: Date;
}

export interface CustomerEvent {
  event_title: string;
  customer: Customer;
  total_budget: number;
  no_of_people: number;
  dates: EventDate[];
}

For initializing, you can follow this approach:

const customerEvent: CustomerEvent = {
  event_title: 'Some Event',
  customer: { /*An Object representing a Customer Type*/ }
  total_budget: 123,
  no_of_people: 456,
  dates: [{
    start_date: new Date(),
    end_date: new Date()
  }]
};

Answer №3

Generate these examples manually:

initializeEvent(customer_event: any) {
    this.event_title = customer_event.event_title;
    this.customer = customer_event.customer;
    this.total_budget = customer_event.total_budget;
    this.no_of_people = customer_event.no_of_people;
    this.dates = customer_event.dates.map(date => new EventDate(date));
}

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

What is the best way to dynamically load a view within a modal based on the clicked link?

I'm looking to optimize the loading of views inside a modal for various operations. Instead of having three separate modals, I want to dynamically load the views based on the link that is clicked. How can I achieve this? Or should I create individual ...

Obtaining a 16-bit integer from the response of an LWIP server

On the server side, I have implemented a loop that takes a 16-bit integer ranging from 0 to 639 and splits it into two 8-bit characters to populate a buffer of 1280 Bytes. The buffer is then sent via TCP-IP to the client. .c unsigned int data2[1000]; ch ...

Executing operations on subdocuments in Mongoose without having to fetch the parent

Currently, when I need to delete a subdocument, I follow this process: Post.findById(post_id).exec(function(err, post) { post.comments.remove({'_id': comment_id}); post.save(function(err) { res.end("Success!"); }); }); This method doe ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

Escape from an iframe with the help of a buster

My website is being targeted by a code that prevents it from breaking out of an iframe. Despite trying different frame breaker scripts, I have not been successful in resolving this issue. Any assistance would be greatly appreciated. Thanks! Buster: func ...

I am having an issue with my registration form in node.js where it does not redirect after submitting

I am currently working on implementing a registration form using node/express for my website. The routes are all set up and the database connection is established. However, I am encountering some issues when users try to submit the registration form on th ...

An ajax call triggers a 500 error response when initiated within another ajax call

I am encountering an issue with my Ajax requests. There are two requests - one (referred to as Ajax#1) sends data to the backend, and the other (Ajax#2) uses that data to load content onto the front end. To ensure that Ajax#2 runs after Ajax#1, I attempt ...

Adding items to a JSON document

My task involves creating a pseudo cart page where clicking on checkout triggers a request to a JSON file named "ordersTest.json" with the structure: { "orders": [] }. The goal is to add the data from the post request into the orders array within the JSO ...

Pressing the HTML button will reveal the cart details in a fresh display box

I have been working on setting up a button to display the items in the shopping cart. I have successfully created the cart itself, but now I am facing the challenge of creating a button called showYourCart that will reveal a box containing the cart detai ...

.ajax() triggers a page refresh upon pressing the ENTER key

Utilizing Ajax to update the database with a new folder leads to page refresh when hitting ENTER. On the form, I have onkeypress="if(event.keyCode==13) savefolder();". Below is the Javascript code where pressing enter calls savefolder function that sen ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Adjustable Bootstrap Progress Bar - Modify element width on the fly

I have encountered an issue with my progress bars on the webpage. The static HTML version works perfectly fine, but the dynamically created one using jQuery seems to be instantly at 100% without any delay in progression. To illustrate the problem better, ...

The date format being sent by Angular to Java is incorrect, resulting in the inability to create an object in the

In my coupon system, I am experiencing an issue with the date format. The Java coupon bean has a date.sql startDate and endDate, while the Angular coupon model includes startDate:Date and endDate:Date in its constructor. However, when I display the dates o ...

Error encountered during Atom execution - The command '/usr/bin/env: 'node' was not found in the directory

Just starting out with coding on Atom and I'm stuck dealing with the same error message every time I try to run my Javascript code. bash: line 1: node: command not found /usr/bin/env: ‘node’: No such file or directory I've searched for solu ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

Include a thousand separator and round to two decimal places in the ngModel input

I have been attempting to format my input values by adding thousand separators and 2 decimals as shown below TS onBlur(event){ if (event.target.value !== ''){ event.target.value = (parseFloat(event.target.value).toFixed(2)).toLocaleS ...

Breaking apart a mesh using THREE.js

Can a single THREE.Mesh be divided into multiple meshes? For instance, can a mesh with 2,000,000 polygons be split into 2,000 meshes each with 1,000 polygons? Edit: Realistically, it may not be possible to retain the exact same number of polygons/vertice ...

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...

Use a jQuery or XPath selector to choose certain HTML tags from a list of HTML tags

Consider this html structure : ... <div class="a">April 2018</div> <div class="b">Monday 02</div> <div class="c">...</div> <!-- Capture this tag and its children --> <div class="c">...</div> <!-- ...

The form fails to submit even after the validation process is completed

My current dilemma involves the validation of an email and checkbox to ensure they are not empty. Although it initially seemed to work, after filling in the required fields and checking the box, I still receive a warning message (.error) and the form fails ...