zoukankan      html  css  js  c++  java
  • 1.filter对数组对象去重时的特殊处理

    1.filter通常情况下是用来返回一个符合条件的新数组的,并且他不会对原数组产生影响:

             comment_or_reply_id: "ob8qj0xq8e5s",
              from_uid: "1502039268@qq.com",
              isAgreeClick: true,
              topic_id: "604629fd0344202df0b22d81",
              topic_type: "nous_articles"
         },
         {
              comment_or_reply_id: "1",
              from_uid: "666",
              isAgreeClick: true,
              topic_id: "604629fd0344202df0b22d81",
              topic_type: "nous_articles"
         }
    ]
    let crr = {
         from_uid: "1502039268@qq.com",
         comment_id: 'ob8qj0xq8e5s'
    }
    let b = arr.filter(function (curentV, index, arr) {
         return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id
    
    })
    console.log(b)

    运行结果:

    [
      {
        comment_or_reply_id: 'ob8qj0xq8e5s',
        from_uid: '1502039268@qq.com',
        isAgreeClick: true,
        topic_id: '604629fd0344202df0b22d81',
        topic_type: 'nous_articles'
      }
    ]

    但是我只是要拿到里面的isAgreeClick怎么做呢?

    这样吗:

    let b = arr.filter(function (curentV, index, arr) {
         return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id
    
    })[0].isAgreeClick
    console.log(b)

    运行结果:true,的确拿到了该值,但是此种做法的弊端就是,当filter里面的条件没有匹配到时,会返回一个空数组,此时对空数组取值就会报错!

    例子:还是刚才那段代码,但是此时comment_or_reply_id为1了,此时匹配不到就会报错

    let arr = [{
              comment_or_reply_id: "1",
              from_uid: "1502039268@qq.com",
              isAgreeClick: true,
              topic_id: "604629fd0344202df0b22d81",
              topic_type: "nous_articles"
         },
         {
              comment_or_reply_id: "1",
              from_uid: "666",
              isAgreeClick: true,
              topic_id: "604629fd0344202df0b22d81",
              topic_type: "nous_articles"
         }
    ]
    let crr = {
         from_uid: "1502039268@qq.com",
         comment_id: 'ob8qj0xq8e5s'
    }
    let b = arr.filter(function (curentV, index, arr) {
         return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id
    
    })[0].isAgreeClick
    console.log(b)

     如何处理呢,下面给出方案:就是把后面数组的返回结果附上布尔值,就可以进行拿到里面的bool值了,但是此种做法只针对布尔值有效,想要拿到里面的其它类型元素的值,

    而且在空数组我下仍然不会报错的话,我暂时没有思路。

    let b = arr.filter(function (curentV, index, arr) {
         return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id
    
    })==false
    console.log(b)

    上面运行结果:

    穷则独善其身,达则兼济天下……
  • 相关阅读:
    集合的遍历和扩容原理
    最新鲜最详细的Android SDK下载安装及配置教程
    开启IIS Express可以调试X64项目
    C# 正则表达式大全
    Windows下SQLMAP的安装图解
    当前比较流行的前端框架2
    前端组件库1
    服务器Windows 登录 出现401 错误
    IPV6配置
    implicit和 explicit关键字
  • 原文地址:https://www.cnblogs.com/hmy-666/p/14617440.html
Copyright © 2011-2022 走看看