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

Looking to combine two arrays by alternating elements from each array in PHP

I am trying to combine two arrays in PHP Array1 = [7,8,9] Array2 = [10,11,12] The desired output would be Array3 = [7,10,8,11,9,12] This means I want the first value of the first array followed by the first value of the second array and so on Can anyone ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Issue with iPad Pro displaying Bootstrap 4 Navbar toggle icon

Having trouble with my Bootstrap 4.1.1 navbar on iPadPro. It's not displaying the correct data from the div and it's not collapsing properly. However, it works fine on small devices. Any suggestions on how to fix this issue? Here's the code ...

Is it possible to postpone the initiation of an Angular application until a promise is fulfilled

At the moment, my code looks like this: new Loader().load().then(() => { platformBrowserDynamic().bootstrapModule(AppModule); }); The issue lies in the fact that I only need to delay the execution of ngOnInit and any route resolving until a prom ...

Updating the DOM after making changes with Maquette involves calling the `renderMaquette

In a previous discussion, I expressed my desire to utilize Maquette as a foundational hyperscript language. Consequently, avoiding the use of maquette.projector is essential for me. However, despite successfully appending SVG objects created with Maquette ...

Error occurs on Chrome while Angular 7 HTTP POST works fine on Edge and Firefox

My application is experiencing a strange issue where the HTTP POST method works fine on Firefox and Edge browsers, but not on Chrome. The application is built using Angular 7 and .NET Core 2.2. It has a CRUD example that functions correctly in all browser ...

Electron Searching for Files in Main Directory

We have developed a web application using Angular 2, but we are facing an issue when trying to run it as an Electron application. After branching out the solution and making changes to package.json to launch Electron on start, we encountered an unexpected ...

Storing data with jQuery

Looking to store objects in jQuery for events. Each event will have a date, title, and some text that needs to be stored in an array. Wondering if using a multi-dimensional array would be the best way to go so I can easily iterate through them with a count ...

Avoid pressing on y mat-button-toogle

In my component, I have a button-toggle like this: <mat-button-toggle-group appearance="legacy"> <mat-button-toggle *ngFor="let session of sessionsArray!"> <fa-icon icon="calendar-alt"></fa-icon> ...

I am interested in utilizing the request-reply pattern with KafkaJS in a TypeScript environment. Could you provide guidance on how to successfully implement this?

I am new to Kafka and I am trying to implement the request-reply pattern using kafkajs in TypeScript. However, my current implementation is very basic and the consumers inside producers are taking too long to start, causing delays. Is there a better way to ...

Trouble with Excel Office Script setInterval functionality

Trying to automatically recalculate an Excel worksheet every second using Office Script. Unfortunately, my initial approach did not succeed. function sendUpdate(sheet: ExcelScript.Worksheet) { console.log('hi'); sheet.calculate(true); } func ...

When I tap on a text element, place the cursor in the input field

I want to set the focus to an input field when I click on a specific piece of text within the same page. What is the most efficient way to achieve this? I already have a function attached to the text element. Below is the code snippet that I am working wit ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Conflicting TypeScript errors arise from a clash between React version 16.14 and @types/hoist-non-react-statics 3.3.1

Currently in the process of upgrading an older project to React 16.14, as we are not yet prepared for the potential breaking changes that would come with moving up to React 17 or 18. As part of this upgrade, I am also updating redux and react-redux to ver ...

Extensible generic type/interface in Typescript

Looking to create a versatile base interface or type that can adapt its properties based on the generic object it receives. It might look something like this: interface BaseObject<Extension extends object = {}>{ a: string; b: string; {...Ext ...

TypeScript fails to acknowledge an exported enum

Currently utilizing TypeScript version 2.5.3 along with Angular 5. I have an enum defined in a separate file as follows: export enum eUserType { Driver = 1, Passenger = 2, User = 3 } To import and use it in another ts file, I do the following: i ...

Tips for including additional properties to a <button> element using ReactJS and Typescript

Currently, I am in the process of creating a unique component which consists of an ordinary <button> tag and has a new prop called aria-current. The issue at hand is that Typescript is flagging an error stating that this property does not exist with ...

What causes error TS2339 to occur: The property 'classList' is not found on type 'never'

Currently, I am working on creating a basic component called "BackToTop" const BackToTop: React.FC = () => { const bttEl = useRef(null); function scrollHandler(): void { var bttHtmlEl: HTMLElement | null = bttEl.current; if (bttH ...

Generating and traversing a JSON object with three dimensions

After exploring various topics on this site, I haven't been able to find a clear solution for my specific problem. I am facing a scenario where I need to populate three select boxes with options from a multidimensional array that follows the structur ...