1.filter对数组对象去重时的特殊处理
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了1.filter对数组对象去重时的特殊处理,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2101字,纯文字阅读大概需要4分钟。
内容图文
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)
上面运行结果:
内容总结
以上是互联网集市为您收集整理的1.filter对数组对象去重时的特殊处理全部内容,希望文章能够帮你解决1.filter对数组对象去重时的特殊处理所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。