type
Post
status
Published
date
Nov 24, 2022
slug
code-4
summary
tags
js
category
学习思考
icon
password
Property
Nov 24, 2022 09:00 AM
有这么一组数据:
let arr = [{ id: '1', key: '1', value: '明月' }, { id: '3', key: '2', value: '可欣' }, { id: '2', key: '3', value: '小红' }, { id: '1', key: '1', value: '小馨' }, { id: '1', key: '2', value: '小静' }]
1、对象访问属性
let newArr = []; let obj = {}; for (var i = 0; i < arr.length; i++) { if (!obj[arr[i].key]) { newArr.push(arr[i]) obj[arr[i].key] = true } }
2、map()
let map = new Map(); for (let item of this.arr) { map.set(item.id, item); } this.arr = [...map.values()];
3、reduce()
reduce () 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数 | 描述 |
total | 必须。初始值,或者计算结束后的返回值。 |
currentValue | 必须。当前元素 |
currentIndex | 可选。当前元素的索引 |
arr | 可选。当前元素所属的数组对象。 |
initialValue | 可选。传递给函数的初始值 |
const obj = {} arr = arr.reduce((total, next) => { obj[next.key] ? '' : obj[next.key] = true && total.push(next) return total }, []) console.log(arr) 这里还有一个需求,如果有两个或者多个判断条件,给数组对象去重,加一个判断条件就行了 const hasObj = {} arr = arr.reduce((total, next) => { const filterKey = next.key + next.id; hasObj[filterKey] ? "" : hasObj[filterKey] = true && total.push(next) return total }, [])
- Author:spike
- URL:https://spiiike.gq//article%2Fcode-4
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!