前端常见的数据处理总结
一、数据去重
1、简单的数组数据去重
//重复的数组
const arr = [1,2,1,3,4,5,1,1,1,1,1]
//ES6新特性去重
const arrFilter = [...new Set(arr)]
console.log(arrFilter) // [1, 2, 3, 4, 5]
2、复杂的去重(在数组对象中带某些重复项属性的去重)
//重复数据
const data = [
{key:0, desc:'JS'},
{key:1, desc:'Less'},
{key:2, desc:'JS'},
{key:3, desc:'React'},
{key:4, desc:'JS'}
]
// 方法一,定义一个常量存储被过滤的数据
const setData = data.filter((item, index) => {
const setIndex = data.findIndex((setItem) => {
return item.desc == setItem.desc
});
return index == setIndex;
})
// 方法二
const setArr = (arr) => {
const res = new Map();
return arr.filter(arr => !res.has(arr.desc) && res.set(arr.desc, 1));
}
console.log(setData)
//0: {key: 0, desc: "JS"}
//1: {key: 1, desc: "Less"}
//2: {key: 3, desc: "React"}
//
3、数组扁平化
// 多维数组
const arr = [ [2, 2, 3], [3, 5, 6], [6, 7, 9, 9, [11, 11, [12, [13], [15] ] ] ], 10];
// ES6新特性去重
// 表示将数组进行扁平化处理,即将n维数组将成1维数组\
// 其中:*Infinity:代表数组维数*
arr.flat(Infinity)
//结果为[2,2,3,3,5,6,6,7,9,9,11,11,12,13,15,10]
二、定义变量时出现的意外
1、深拷贝问题的解决
// 没有解决深浅拷贝
const Tant = {
age:12,
sex:'man',
}
const Eane = Tant
Eane.age = 89
console.log(Eane.age, Tant.age) // 89 89
// 解决了之后
// 这并不严谨,建议还是用lodash的深拷贝,或者自写递归做处理。
const Tant = {
age:12,
sex:'man',
}
const Eane = JSON.parse(JSON.stringify(Tant))
Eane.age = 89
console.log(Eane.age, Tant.age)// 89 12
三、小数运算精度丢失
1、用parseFloat来保证浮点型,用toFixed修饰小数点数位
// 没有解决精度问题
const noFixed = 0.2955 * 100
console.log(noFixed) // 29.549999999999997
// 解决了精度问题之后
const fixed = parseFloat((0.2955 * 100).toFixed(2))
console.log(fixed) // 29.55
四、数组对象数据按照某个关键值分类
1、运用ES6设置对象值的方式 A[a]
var test=[
{
id:1,
name:'a'
},{
id:2,
name:'a'
},{
id:1,
name:'a'
},{
id:3,
name:'a'
},{
id:4,
name:'a'
}
]
const classify = (data, key) => {
const group = {}
// 对data通过key进行分类
data?.forEach(item=>{
group[item[key]] = group[item[key]] || []
group[item[key]].push(item)
})
return group
}
运行classify(test,'id')得到
{
"1":[{"id":1,"name":"a"},{"id":1,"name":"a"}],
"2":[{"id":2,"name":"a"}],
"3":[{"id":3,"name":"a"}],
"4":[{"id":4,"name":"a"}]
}
将开发中遇到的一些数据问题,就此做了小总结,后续会继续总结意义能有效复用case,如果那儿有问题可以在评论中指出。