简体   繁体   中英

How do i save multiple objects into an array

I have this object after click the save button.

{description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "2", hr_id: 
72, …}

But whenever i click on save, it gives me a new object instead of storing it in array. The question is how can i store each object inside an array to get

[
{description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "1" …},
{description: "grrrhhg", dateSelected: "2020-03-27", startDate: "2020-03-27", company_id: "2" …},
{description: "ghrtrhg", dateSelected: "2020-04-27", startDate: "2020-04-27", company_id: "2",  …},
.
.
.
]

This is my code

saveHolidays(hols : []){
 this.holidays.hr_id = this.hrID.id;
 this.getHolidayDate = this.holidays.dateSelected.split(" to ");
 this.holidays.startDate = this.getHolidayDate[0];
 this.holidays.endDate = this.getHolidayDate[1];
 this.getHols = this.holidaysData;
 this.holiday_date = [];
 this.holidaysArray = [];
 var tempHolidays = [];
 this.getHols.forEach((element,key) => {
   if(element.startDate){
     this.holiday_date.push({startDate : element.startDate, endDate : element.endDate, company_id : 
  element.company_id})
   }
 });
 var getElement = [];
 let getStartDate = this.holiday_date.map(element => {
 getElement.push(element.startDate, element.company_id);
 return getElement;
 });

 for(var i = 0; i < getStartDate.length; i++){
  var isStartDatePresent = getStartDate[i].includes(this.holidays.startDate);
  var isCompanyIdPresent = getStartDate[i].includes(+this.holidays.company_id);
 }
 if(isStartDatePresent == true && isCompanyIdPresent == true ){
   this.snotifyService.error('Holiday Already Exist');    
 }else{
   hols = this.holidays;
   for(var i = 0; i < hols.length; i++){
     this.holidaysArray.push(hols[i]);
   }

  return this.holidaysArray
 }
}

I'm a bit rusty, but if I remember correctly, JS arrays don't have fixed widths, so you might be able to push each saved holiday to an externally instantiated array or return one and set the desired external array to it.

You are reinitializing your array every time you click on save button by writing this.holidaysArray . Removing it might solve your problem.

Set this.holidaysArray to an array ONLY IF it not already an Array .

/* REPLACE */
    this.holidaysArray = []
/* WITH */
  if (!Array.isArray(this.holidaysArray)) {
    this.holidaysArray = []
  }

Also, I highly recommend using a test-framework like Jest to test your code.

Good Luck...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM