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)

    上面运行结果:

    穷则独善其身,达则兼济天下……
  • 相关阅读:
    fopen vs fsocketopen vs curl
    php parallel
    《PHP扩展开发及内核应用》
    在CentOS上搭建PHP服务器环境
    mysql 慢查询记录方法
    python的线上环境配置
    python, Django csrf token的问题
    python 安装mysqldb组件
    python 升级到python2.7
    Django的Hello World
  • 原文地址:https://www.cnblogs.com/hmy-666/p/14617440.html
Copyright © 2011-2022 走看看