cdub
cdub

Reputation: 25711

Using forEach in an array to find an object and change it's value in TypeScript

I have a statement like so:

private updateVariable(anId:number): void {

    this.model.forEach(q => 
        {
            q.anId === anId && (q.isUpdated = !q.isUpdated)
        });

The model is defined as:

private model:Array<IMyData> = [];

Also IMyData is defined with this:

export interface IMyData{
    anId:number;
    isUpdated:boolean;
}

The goal is to iterate over the data to find the matching anId and:

change isUpdated from:

null and false to true

and from:

true to false

Thanks in advance.

Upvotes: 0

Views: 145

Answers (1)

KShewengger
KShewengger

Reputation: 8269

You can do it in 1 line instead. Using Array's .map()

const anId = '123';

this.model = this.model.map(item => item.anId === anId ? {...item, isUpdated: !item.isUpdated} : item)

console.log(this.model);     // to check the array with it's updated data

Upvotes: 1

Related Questions