firasKoubaa
firasKoubaa

Reputation: 6867

Typescript : reuse both of for .. of and for .. in at same level

I want to reuse "for .. of " to loop over an array of objects , at same time i want to get the index inn each time (with : for.. in).

so that i can change a specifc object with another accortding to its index.

My purpose is to loop over a list , find a specifc object by its name attribute , and change it with another object.

updateObjectInList(list, newObject) {

    for(let item of list , let index in list ){
      if (item.name=== newObject.name){
        list[index] = newObject
      }
    }

}

Of course this stament " let item of list , let index in list " is not working

Suggestions ?

Upvotes: 1

Views: 55

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take an iterator of the entries of the array and get index and value at the same time.

var array = [33, 22, 11];

for (const [index, value] of array.entries()) {
    console.log(index, value);
}

Upvotes: 3

Related Questions