js中数组对象去重的两种方法
2019/6/26 23:15:39
本文主要是介绍js中数组对象去重的两种方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
方法一:
采用对象访问属性的方法,判断属性值是否存在,如果不存在就添加。
方法二:
采用数组中的reduce方法,遍历数组,也是通过对象访问属性的方法
var arr = [{ key: '01', value: '乐乐' }, { key: '02', value: '博博' }, { key: '03', value: '淘淘' },{ key: '04', value: '哈哈' },{ key: '01', value: '乐乐' }]; // 方法1:利用对象访问属性的方法,判断对象中是否存在key var result = []; var obj = {}; for(var i =0; i<arr.length; i++){ if(!obj[arr[i].key]){ result.push(arr[i]); obj[arr[i].key] = true; } } console.log(result); // [{key: "01", value: "乐乐"},{key: "02", value: "博博"},{key: "03", value: "淘淘"},{key: "04", value: "哈哈"}] // 方法2:利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数,第二个参数是item的初始值 var obj = {}; arr = arr.reduce(function(item, next) { obj[next.key] ? '' : obj[next.key] = true && item.push(next); return item; }, []); console.log(arr); // [{key: "01", value: "乐乐"},{key: "02", value: "博博"},{key: "03", value: "淘淘"},{key: "04", value: "哈哈"}]
若有不足请多多指教!希望给您带来帮助!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对找一找教程网的支持。如果你想了解更多相关内容请查看下面相关链接
这篇关于js中数组对象去重的两种方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist
- 2024-03-11icons for vue
- 2024-03-07breadcrumbs react js
- 2024-03-06react login page example
- 2024-03-06react router uselocation
- 2024-03-04postgres jsonb_set