数据各种去重复,合并方法
1,数组对象去重通过id
function reduce(arr) {
var obj = {};
arr = arr.reduce(function (item, next) {
obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
return item;
}, []);
return arr;
}
合并对象数据深度
function deepMerge(obj1, obj2) {
let key;
for (key in obj2) {
obj1[key] =
obj1[key] &&
obj1[key].toString() === "[object Object]" &&
obj2[key] &&
obj2[key].toString() === "[object Object]"
? deepMerge(obj1[key], obj2[key])
: (obj1[key] = obj2[key]);
}
return obj1;
}
3,深度复制拷贝数据
function judgeType(obj) {
const toString = Object.prototype.toString;
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object',
};
if (obj instanceof Element) {
return 'element';
}
return map[toString.call(obj)];
}
export function deepClone(data){
const type = judgeType(data);
let obj;
if (type === 'array'){
obj = [];
} else if (type === 'object') {
obj = {};
} else {
// 不再具有下一层次
return data;
}
if (type === 'array'){
for (let i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]));
}
} else if (type === 'object') {
// 对原型上的方法也拷贝了....
for (const key in data) {
obj[key] = deepClone(data[key]);
}
}
return obj;
}
版权声明:本文由Web学习之路发布,如需转载请注明出处。