Home > OS >  Create an array while iterating Angular
Create an array while iterating Angular

Time:12-07

I am getting the IDs from an array when I select a few rows (a lot of data is coming in and I only need the IDs). I want that when obtaining the IDs an array is created for me ONLY with the IDs. The problem is that when I try I get the following (by console):

Id Seleccionado: 78
Id Seleccionado: 79
Id Seleccionado: 81

And I would like to obtain them as a normal array:

{ 78, 79, 81 }

TS

procesarClic() {
    const request = this.selection.selected;
    for (let i = 0; i < request.length; i  ){
      const list = request[i].id;
      console.log('Id Seleccionado: ', list);
    }
}

The request constant it is where the selected rows are with all the data in the array, since many rows can be selected.

Thank you for your contribution and help!

CodePudding user response:

You have to create the array and filling it up like this:

procesarClic() {
    const request = this.selection.selected;
    let array = [];
    for (let i = 0; i < request.length; i  ){
      const list = request[i].id;
      console.log('Id Seleccionado: ', list);
      array.push(request[i].id);
    }
}

This way, you will have an array with only ids in it.

BR

CodePudding user response:

Assuming this.selection.selected is an array which it seems to be, you could use the map function, ie.

const examples = [
  {id: 1, name: "One"},
  {id: 2, name: "Two"},
  {id: 3, name: "Three"}
]

const onlyIds = examples.map(e => e.id);

console.log(onlyIds);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

which would return an array consisting of ids only.

  • Related