vuelidate icon indicating copy to clipboard operation
vuelidate copied to clipboard

Avoid data duplication in a collection

Open jeangomes opened this issue 5 years ago • 5 comments

Is there an simple way?

jeangomes avatar May 02 '19 18:05 jeangomes

Please give a better explanation to your issue.

dobromir-hristov avatar May 03 '19 05:05 dobromir-hristov

I'm using oficial sample to illustrate my doubt. https://vuelidate.netlify.com/#sub-collections-validation The question is, how avoid repeated items in a collection, like individual names.

jeangomes avatar May 03 '19 13:05 jeangomes

You want to validate whether an array has repeating items? If so, then a custom validator function would be best

dobromir-hristov avatar May 04 '19 12:05 dobromir-hristov

If this is resolved, please close the ticket.

dobromir-hristov avatar May 09 '19 18:05 dobromir-hristov

Hi. I know this is an old issue but this is the first result when I searched about data duplication in collections.

To solve this, you can create a custom validator like this:

export const unique = (group, key) => {
  return (value) => {
    const found = group.filter(item => {
      if (key) {
        return item[key] == value;
      }
      return item == value;
    });
    return found.length <= 1;
  };
}

Now, in your component:

...
validations () {
  return {
    candies: {
      unique: unique(this.candies),
    },
    cookies: {
      $each: {
        name: {
          unique: unique(this.cookies, 'name'), // for array of objects
        },
      },
    },
  };
},
...

This solution is fine and works, but it can be improved. The downsides are:

  1. You have to pass the array where the property belongs.
  2. If it's an array of objects, you have to pass the key of the property.

I wanted to solve this but I haven't found anything in the docs.

shino47 avatar Jan 24 '20 22:01 shino47