我想将对象或对象数组推送到现有数组,并保持数组中的元素唯一

时间:2017-03-31 08:15:15

标签: javascript arrays

当它是一个对象时,我可以使用这种方法来获得我想要的东西

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
   }

有没有办法做到这一点?如果它是下面的对象数组(例如obj1),如何将对象数组(例如obj1)推送到现有数组(例如数组),并保持数组(数组)中的元素唯一?< / p>

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'}
    ]

1 个答案:

答案 0 :(得分:0)

查看lodash.unionBy

以下是一个例子:

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