【问题标题】:unique objects by value and extra filter within an array of objects对象数组中按值和额外过滤器的唯一对象
【发布时间】:2021-04-30 15:01:16
【问题描述】:

我正在尝试在对象数组中获取唯一对象。假设对象如下所示。

    values = [
      { id: 10, available: true },
      { id: 10, available: false },
      { id: 11, available: true },
      { id: 12, available: false }
    ];

唯一的对象应该返回如下:如果重复的对象包含available:true需要available:true

    result = [
      { id: 10, available: true },
      { id: 11, available: true },
      { id: 12, available: false }
    ];

【问题讨论】:

    标签: arrays filter javascript-objects reduce on-duplicate-key


    【解决方案1】:

    解决您的问题.. 函数myfilter() 返回一个具有唯一id 值的数组,如果存在available: true 则优先

    var values = [
          { id: 10, available: true },
          { id: 10, available: false },
          { id: 11, available: true },
          { id: 12, available: false }
        ];
        
    function myfilter()
    {
        var filtarray=[];
        values.forEach(function(element) {
    
            var idxfound = filtarray.findIndex(function(ele2) {
                return ele2.id === element.id;
            });
            
            if (idxfound==-1)
            {
              filtarray.push(element);
            }
            else {
                if (filtarray[idxfound].available==false && element.available==true)
                filtarray[idxfound].available=true;
            }
    
        });
        
        console.log(filtarray);
        return filtarray;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多