Aragorn8806
Aragorn8806

Reputation: 27

Create an array while iterating Angular

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!

Upvotes: 0

Views: 1071

Answers (2)

Aldin Bradaric
Aldin Bradaric

Reputation: 803

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);

which would return an array consisting of ids only.

Upvotes: 0

VitoCK
VitoCK

Reputation: 415

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

Upvotes: 1

Related Questions