1.filter对数组对象去重时的特殊处理

2021-06-06 03:03

阅读:340

[
  {
    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)

上面运行结果:技术图片

 

 

 

 

 

上一篇:spring-service.xml

下一篇:java注释


评论


亲,登录后才可以留言!