0

So I have a data structure like this:

formSubmissions: [
    {
        ids: [1,2,3,4,5],
        genders: ["male", "female"],
        times: ["1day","3days"]
    },
    ...
]

Basically, every time a form is submitted, I want to check if the object created from the three fields in the form, is equal to anything in the formSubmissions array. If not, I want to append it to the array.

What is the fastest way to accomplish this? I have tried some other stack overflow solutions to no avail.

Thanks!

Tim B.
  • 446
  • 1
  • 5
  • 13

3 Answers3

1

If you are on Nodejs and all you need is to compare objects by their contents, util.isDeepStrictEqual() can be useful:

if (!this.formData.some(elem => util.isDeepStrictEqual(elem, submitted))) {
    this.formData.push(submitted);
}

But please note that array values in different objects will not match if their ordering is different.

Luc125
  • 5,752
  • 34
  • 35
0

Heres what I came up with while waiting for a response:

if (!(this.formData.some(el => el.voIds === submitted.voIds && 
                               el.genderList === submitted.genderList && 
                               el.times === submitted.times))) {
        this.formData.push(submitted);
      }

It seems to work. Any suggestions on how it can be improved?

Tim B.
  • 446
  • 1
  • 5
  • 13
  • Even if it works, it looks difficult to maintain in case the structure of your objects evolve, that's why I would advise using a function for this – Luc125 May 13 '20 at 19:53
  • You're totally right. If i expect it to change, I will move to your solution. At the current time though, I don't think it will ever change. – Tim B. May 13 '20 at 22:13
0

Another solution, using Lodash _.isEqual() as per the accepted answer in How to do a deep comparison between 2 objects with lodash?

if (!this.formData.some(elem => _.isEqual(elem, submitted))) {
    this.formData.push(submitted);
}

Note that as other Lodash utilities, it is available as a standalone NPM package, so you do not have to depend on the rest of the library.

Luc125
  • 5,752
  • 34
  • 35