1

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!

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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?

2 Comments

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
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.

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.