0

when it's an Object i can use this method to get what i want

var obj=  {value: 'mouseup', label: 'mouseup'};

    var array = [
        {value: 'mouseup', label: 'mouseup'},
        {value: 'mousedown', label: 'mousedown'},
        {value: 'mousemove', label: 'mousemove'},
        {value: 'mouseover', label: 'mouseover'},
        {value: 'mouseout', label: 'mouseout'}
    ]

   function pushUnique(obj) {
        for (var i = 0; i < array.length; i++) {
            if (array[i].value === obj.value) { 
            return array;
            }
        }
        array.push(obj);
        return array
   }

Are there any methods to do this? What if it's an Array of Objects below(e.g obj1),how can i push an Array of Objects(e.g obj1) to an existed Array(e.g array),and keep elements in the Array(array) unique ?

obj1=  [
        {value: 'hover', label: 'hover'},
        {value: 'click', label: 'click'},
        {value: 'mouseup', label: 'mouseup'},
        {value: 'mousedown', label: 'mousedown'},
        {value: 'mousemove', label: 'mousemove'},
   ]

array = [
        {value: 'mouseup', label: 'mouseup'},
        {value: 'mousedown', label: 'mousedown'},
        {value: 'mousemove', label: 'mousemove'},
        {value: 'mouseover', label: 'mouseover'},
        {value: 'mouseout', label: 'mouseout'}
    ]
Cele King
  • 95
  • 11

1 Answers1

0

Check out lodash.unionBy

Here is an example:

// The `_.property` iteratee shorthand.
_.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]
Amir Hoseinian
  • 2,312
  • 2
  • 24
  • 27