【问题标题】:I want to push an Object or an Array of Objects to an existed Array,and keep elements in the Array unique我想将一个对象或对象数组推送到现有数组,并保持数组中的元素唯一
【发布时间】:2017-03-31 08:15:15
【问题描述】:

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

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)推送到现有数组(例如数组),并保持数组(数组)中的元素唯一?

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

【问题讨论】:

标签: javascript arrays


【解决方案1】:

查看lodash.unionBy

这是一个例子:

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

【讨论】:

    猜你喜欢
    • 2019-12-22
    • 1970-01-01
    • 2016-05-28
    • 2018-08-10
    • 2019-04-11
    • 1970-01-01
    • 2013-10-07
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多