Home > Enterprise >  Assign each value to object
Assign each value to object

Time:05-12

I am taking data from my backend in this simple way

this.archiveService.getRooms(team).subscribe(
  res => {
   this.form = res;
    this.form.forEach(el => {
     el.reservation.slice(-6).match(/.{1,2}/g).join('/');
    });

  },
  error => {
    console.log(error);
  }
)

this.form is a Object I am getting reservation number from form then I want to slice everything that I don't want. ( Regex works fine ). Then I want to assign this prepared value into my this.form then I using *ngFor in table

How can I assign each value from forEach loop into this.form

CodePudding user response:

Propose of .foreach() doesn't serve what you want.

However, If you feel the life is quite ordinary and want to do some advance. Check is out Array.prototype.forEach()

CodePudding user response:

As read in the documentation, the js slice method

Return A new array containing the extracted elements.

In fact, the slice methods does not modifiy the current element of the array


To solve your problem, you can either use the splice methods which works as the following :

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().

this.form.forEach(el => {
     el.reservation.splice(-6).match(/.{1,2}/g).join('/');
    });

Or re-assign the value using the slice method

this.form.forEach(el => {
     el.reservation = el.reservation.slice(-6).match(/.{1,2}/g).join('/');
    });

Small example of usage

const myArr = [1,2,3,4,5,6,7,8,9,10]

const returnVal = myArr.slice(0,5)

console.log(`val return by slice : ${returnVal}`)
console.log(`current arr : ${myArr}`)

console.log('------------------')


const myArr2 = [1,2,3,4,5,6,7,8,9,10]

const returnVal2 = myArr2.splice(0,5)

console.log(`val return by splice : ${returnVal2}`)
console.log(`current arr : ${myArr2}`)

  • Related