0

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.

9
  • 3
    Do you get any error with the above statement? Commented Oct 15, 2020 at 6:36
  • Why do you need to use forEach when you can do it using filter? Commented Oct 15, 2020 at 6:37
  • 1
    @KiranShakya that's not what the code is doing. Commented Oct 15, 2020 at 6:39
  • If you don't mind null being changed to false, you could just write q.isUpdated = q.isUpdated ^ (q.anId === anId) Commented Oct 15, 2020 at 6:42
  • This code doesn't look bad, what's wrong with it? You didn't say what the problem is Commented Oct 15, 2020 at 6:42

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.