0

I have action, which add new object to a store:

let warning = {message: 'some text', status: 'suspended'} 
this.store.dispatch(new WarningActions.AddWarning(warning))

but if I already have the same warning, I don't want to add it again, so I tried to check store before dispatch it:

this.store.select('warning').subscribe(warnings => {
   console.log(warnings) // [{message: 'some text', status: 'suspended'}]
   if (warnings.indexOf(warning) === -1) {
     this.store.dispatch(new WarningActions.AddWarning(warning))
   }
})

But this is does not work, because warnings.indexOf(warning) === -1 always yields true, even if I already have exactly the same object. What I did wrong and how I can solve this?

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70

2 Answers2

1

indexOf() will always return -1 because they are two distinct objects and cannot equal even if they look the same (i.e. have the same properties and values).

you may use the some method to find if the properties are same.

iams0nus
  • 481
  • 3
  • 8
1

You can not deeply compare objects in Javascript this way. {} === {} is false no matter what you do. You need to compare the properties manually. If you want deep comparison in JS have a look at this post.

Felix Lemke
  • 6,189
  • 3
  • 40
  • 67