ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-04-04 23:35:13  阅读:250  来源: 互联网

标签:comment crr uid curentV filter 重时 数组 reply id


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)

上面运行结果:

 

 

 

 

 

标签:comment,crr,uid,curentV,filter,重时,数组,reply,id
来源: https://www.cnblogs.com/hmy-666/p/14617440.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有