0

Having the file app.component.ts, inside its class it is declared a variable of which stores from the input a date.

I want with that date to create an object, the key being the date and the value being a boolean ( which is true or false depending on the date, for example if the date is inside year 2018 it is false, otherwise it's true)

Html file:

<input type="date" [(ngModel)]="currentDate">
<button (click)="addDate()">add date</button>

ts:

export class AppComponent {
    dateArray = [];
    currentDate = "";
    dateObject = { this.currentDate, true };
    addDate() {
         this.dateArray.push(dateObject);
    }
}

I'm new to Angular, I don't know how dateObject should look like in order to store in it what I want. Any suggestions?

cs95
  • 379,657
  • 97
  • 704
  • 746
Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • Possible duplicate of [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – cs95 Oct 27 '19 at 00:37
  • The answer is to use `{[this.currentDate]: true}` but you should initialise `dateObject` inside `addDate` otherwise you will only append the same object each time. – cs95 Oct 27 '19 at 00:39

2 Answers2

1

You can create a class that contains the properties that you want. Example

export class MyCustomClass {
   public currentDate: Date;
   public isDateValid: boolean;
   constructor(currentDate: Date) {
     this.currentDate = currentDate;
     if(currentDate.getFullYear() < 2018) { 
        this.isDateValid = false;
     } else {
        this.isDateValid = true;
     }
   }
}

Then you can create a instance of MyCustomClass in the AppComponent

export class AppComponent {
    dateArray: MyCustomClass[] = [];
    currentDate = "";
    newObj: MyCustomClass;
    addDate() {
         newObj = new MyCustomClass(currentDate);
         this.dateArray.push(newObj);
    }
}

Is that what you need?

German Quinteros
  • 1,870
  • 9
  • 33
1

This is what you can do:

export class AppComponent {
    dateArray = [];
    currentDate = "";
    addDate() {
      const currentYear = new Date(this.currentDate).getFullYear();
      if (currentYear === 2018) { 
        this.dateArray.push({
          [this.currentDate]: true
        });
      }

    }
}

You can convert the currentDate string into a JavaScript Date Object, followed by using the Date.getFullYear() method to get the year.

Then, you can proceed to check if the year is 2018, before pushing the object into the dateArray.

In addition, the way you are initialising the dateObject is a wrong use of working with object literals. For this scenario, you should be working with computed property names instead, such as { [this.currentDate]: true }.

wentjun
  • 40,384
  • 10
  • 95
  • 107