列表去重
使用 Set 数据结构
- const set = new Set([2, 8, 3, 8, 5])
注:Set 数据结构认为对象永不相等,即使是两个空对象,在 Set 结构内部也是不等的
方法封装
- const uniqueness = (data, key) => {
- const hash = new Map()
- return data.filter(item => !hash.has(item[key]) && hash.set(item[key], 1))
- }
对象转为查询字符串
代码注释
- /**
- * @description: 对象转为查询字符串
- * @params {Object} data: 源数据
- * @return {String} 目标数据
- * @example
- *
- * serialize({ a: 1, b: 2 })
- *
- * a=1&b=2
- */
方法封装
- export const serialize = data => {
- return Object.keys(data).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`).join('&')
- }
获取查询参数
代码注释
- /**
- * @description: 获取查询参数
- * @params {String} name: 查询参数名称
- * @return {String} 目标数据
- * @example
- *
- * getQueryString('id')
- */
方法封装
- export const getQueryString = key => {
- return (new URLSearchParams(location.search)).get(key)
- }
扩展封装
- class Route {
- static url = new URL(location)
- static attr(attribute) {
- return this.url[attribute]
- }
- static getParams() {
- const { searchParams } = this.url, params = {}
- for (const [key, value] of searchParams.entries()) {
- params[key] = value
- }
- return params
- }
- static getParam(name) {
- const { searchParams } = this.url
- return searchParams.get(name)
- }
- static hasParam(name) {
- const { searchParams } = this.url
- return searchParams.has(name)
- }
- }
以上就是JS数据分析数据去重及参数序列化示例的详细内容,更多关于JS数据去重参数序列化的资料请关注w3xue其它相关文章!