js 對象去重的方式


一般在開發的過程中,都會碰到處理數據的數組去重或者對象去重,以下是去重的方式
第一種方式: 
// 對象根據條件去除重復數據
RemoveDuplication(arr) {
const hash = {}
arr.reduce((obj, next) => {
const hashId = `${next.date}_${next.userId}` // next.date和userId是去重的條件
if (!hash[hashId]) {
hash[`${next.date}_${next.userId}`] = true
obj.push(next)
}
console.log(obj)
return obj
}, [])
},
 
再簡化一下還可以寫成
const arr = this.tableCheckbox.reduce((item, next) => {
     obj[next.id] ? '' : obj[next.id] = true && item.push(next)
     return item
}, [])
 
第二種方式:
es6里面的new Set方法  一般多用於數組去重
也可以使用對象的去重方式
new Set(newArrList)// 去重
 
/*** 數組中對應數組對象中的值,不需要重新寫一個變量直接就可以刪除數據,只留下對應的數據   */
const dateArr = [1,3,16,20]
const schedual = [{name: '香蕉', id: 1}, {name: '梨', id: 6},{name: '蘋果', id: 16}, {name: '橘子': 7}]
// 根據dateArr中的數據,將 schedual里面的數據過濾
 
schedual = schedual.filter(item => {
       return dateArr.indexOf(item.name) > -1 // 要檢索的字符串值沒有出現
})
consolelog(schedual) // [{name: '香蕉', id: 1},{name: '蘋果', id: 16}]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM