Working with Array of Objects Within Another Array in Angular 6 Using Typescript

I'm currently working with an array of "food":

"food": [
 { 
    "id": 11,
    "name": "Kabeljaufilet",
    "preis": 3.55,
    "art": "mit Fisch"
},
{
  "id": 12,
  "name": "Spaghetti Bolognese",
  "preis": 3.85,
  "art": "mit Fleisch"
},
{
  "id": 13,
  "name": "Pizza Salami",
  "preis": 3.99,
  "art": "mit Fleisch"
},

Now, I am looking to create another Array called "foodplan" where I can manage the foods from the first array by adding or deleting them.

This is my first time working with Arrays that contain Objects from other Arrays. Can you guide me on how to proceed?

Foodplan should have attributes like FoodPerWeek, containing 5 food objects, and WeekNumber Foodplan needs methods for showFood, addFood, changeFood, and deleteFood.

Answer №1

This is a simple illustration. Feel free to adjust the array size dynamically if you prefer. Make sure to include input validation checks before implementing other functionalities. Enjoy experimenting!

enum WeekDay {
  Monday = 0,
  Tuesday = 1,
  Wednesday = 2,
  Thursday = 3,
  Friday = 4
}

class Food {
  public id: number
  public name: string
  public price: number
  public type: string
}

class FoodPlan {
  private weeklyFood: Food[] = new Array(5)

  addFood(food: Food, weekDay: WeekDay) {
    this.weeklyFood[weekDay] = food
  }

  showFood(weekDay: WeekDay) {
    console.log(this.weeklyFood[weekDay])
  }

  remove(weekDay: WeekDay) {
    this.weeklyFood[weekDay] = null
  }
}
let foodPlan: FoodPlan = new FoodPlan()
let firstFood: Food = new Food()

firstFood.id = 1
firstFood.name = "Cod Fillet"
firstFood.price = 3.55
firstFood.type = "with Fish"

foodPlan.addFood(firstFood, WeekDay.Wednesday)
foodPlan.showFood(WeekDay.Wednesday)
foodPlan.remove(WeekDay.Wednesday)

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

Transform the API response array into a different format, ready to be passed as a prop to a

Looking to incorporate the Vue Flipbook component into my project, which requires an array of image URLs for the "pages" prop. I am fetching post responses from the WordPress REST API. My goal is to extract the "image" property from the response array and ...

Formatting the string value

Having trouble formatting the input value. Take a look at this code snippet: <input type="text" class="form-control" name="time" formControlName="time" (input)="convertToMinute($event.target.value)" /> Here is the function in question: ...

TypeORM does not have the capability to specify the database setting within the entity decorator

As my TypeORM project grows in size and its components become more discreet yet interconnected, I am exploring ways to separate it into multiple databases while maintaining cross-database relations. To achieve this, I have been experimenting with the data ...

Installation of ag-grid was unsuccessful

Having trouble with this command and error message, any suggestions on how to resolve it? npm install --save ag-grid-community ag-grid-angular https://www.ag-grid.com/angular-grid/getting-started/ ...

React: Implement a feature to execute a function only after the user finishes typing

Currently, I am using react-select with an asynchronous create table and have integrated it into a Netsuite custom page. A issue I am facing is that I would like the getAsyncOptions function to only trigger when the user stops typing. The problem right now ...

Modify the parent property's value within a derived Angular service

I'm utilizing Angular 9 and I have Service A along with Service B which extends Service A. Within Service A, there's a specific property that I aim to modify its value from within Service B. Surprisingly, the change only reflects in Service B and ...

Filtering data from a list of objects in Angular when clicked

0: {user_id: 1, status: Active, account_request_status: 2, first_name: null, last_name: null, email: null,…} 1: {user_id: 3, status: Inactive, account_request_status: 0, first_name: null, last_name: null, email: null,…} 2: {user_id: 37, status: Rejecte ...

Encountering trouble installing Angular CLI on MacOS High Sierra version 10.13.2

I am encountering an issue while trying to install Angular CLI. I have successfully installed the latest NodeJs version 8.9.4 and npm version 5.6.0. However, when I attempt to run the command npm install -g @angular/cli, I receive the following error messa ...

Getting meta values in Angular2 is a common task that can be achieved through

Is there a way to retrieve the meta value from the HTML head in Angular2? For instance, let's say I have the following HTML structure of my project and I want to extract the meta tag with the name "userId". <!doctype html> <html> <he ...

Developing a common module for use across deferred loading paths

I have been working on developing an Angular 11 application and am currently in the process of creating a SharedModule. My goal is to prevent loading common modules repeatedly across my lazy loaded routes. To achieve this, I created a shared module and imp ...

The constant increase in page header number leading to minor interruptions during page scrolling

On my website, I have a dynamic page header that shows the number of comments a user has scrolled through. You can see this feature in action here: However, there seems to be a slight jitter on the screen every time the comment counter updates... To disp ...

Angular 5 Service Unit Testing for UPDATE Function

Currently, I am implementing a stepper feature with back, step, next steps. On the last step, when the user clicks 'done,' I need to call a service to update user data. While I have successfully tested the backStep() and nextStep() methods, I now ...

Exploring VueJS reactivity: Updating an array with new data

I am struggling to understand why certain methods of changing data seem to work while others do not. In an attempt to clarify, I experimented with the following example: watch: { '$store.state.linedata': function() {this.redraw()} } ...

Sending a two-dimensional C array to Python NumPy

Could someone assist me in passing a C array to Python (numpy)? I have a 2D array of doubles with NumRows x NumInputs, but it seems that using PyArray_SimpleNewFromData is not converting it correctly. The debugger only shows pointers which makes it hard to ...

Extract data from a JSON-encoded array using JavaScript

I sent a JSON encoded array to JavaScript. Now I want to access that array to retrieve the different elements. When I print it out using console.log(), I see this array: array(1) { [16]=> array(2) { [3488]=> array(1) { [0]=> ...

The identical package.json file is incompatible with both Windows and Mac operating systems, resulting in errors when

I encountered an error while trying to launch my app on Windows. basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") [0] ^^^^ [0] ^^^ [0] [0] SyntaxError: missing ) after argument list Can anyone provide insights on what m ...

Using react-google-charts to create visually appealing dual-Y stacked bar charts

I am currently working on developing a bar chart with specific criteria in mind. My data follows the format: [month, region, totalSalesForCompanyA, totalSalesForCompanyB] I have successfully implemented the following charts: A dual-Y bar chart where mo ...

Angular6 HttpClient: Unable to Inject Headers in Get Request for Chrome and IE11

Under my Angular 6 application, I am attempting to make a GET request while injecting some custom Headers: Here is how my service is structured: @Injectable() export class MyService { constructor(public httpClient: HttpClient) { } getUserInfos(login): Ob ...

"Trouble with Angular reactive form submission - selected options not being passed through

I have a form that is dynamically populated with multiple select inputs: <form [formGroup]="searchForm" (ngSubmit)="onSubmit(searchForm.value)"> <div class="col-md-2" *ngFor="let filter of this.filters; index as i"> <div class="for ...

Service consuming in Angular 2 using Stomp protocol

Why am I seeing responseBody as undefined, but I am able to see the subscribe response in msg_body? What could be causing this issue with responseBody? let stomp_subscription = this._stompService.subscribe('/topic/queue'); stomp_subscription.ma ...