数组对象去重
- 方法1:利用对象访问属性的方法,判断对象中是否存在key、value
const arr = [ { key: "1", value: "西瓜" }, { key: "1", value: "苹果" }, { key: "3", value: "桃子" }];const list = [ { key: "1", value: "哈密瓜" }, { key: "2", value: "黄瓜" }, { key: "3", value: "黄瓜" }];function unique (obj1,obj2,targe) { const data = []; // 创建一个新数组 const obj = {}; // 创建一个新对象 const list = obj1.concat(obj2); for (let i=0; i< list.length; i++) { if (!obj[list[i][targe]]) { // 判断对象不存在key、value data.push(list[i]); obj[list[i][targe]] = true; } } return data;} console.log( unique(arr, list, "value"));复制代码
- 方法2:利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数,第二个参数是item的初始值
const arr = [ { key: "1", value: "西瓜" }, { key: "1", value: "苹果" }, { key: "3", value: "桃子" }];const list = [ { key: "1", value: "哈密瓜" }, { key: "2", value: "黄瓜" }, { key: "3", value: "黄瓜" }];function unique (obj1,obj2,targe) { const obj = {}; // 创建一个新对象 const list = obj1.concat(obj2); const data = list.reduce(function(item,next) { if (!obj[next[targe]]) { item.push(next) obj[next[targe]] = true; } return item; }, []); return data;} console.log(unique(arr, list, "value"));复制代码
const arr = [ { key: "1", value: "西瓜" }, { key: "1", value: "苹果" }, { key: "3", value: "桃子" }];const list = [ { key: "1", value: "哈密瓜" }, { key: "2", value: "黄瓜" }, { key: "3", value: "黄瓜" }]; function unique(obj1,obj2,targe) { const data = [...obj1, ...obj2]; const res = new Map(); return data.filter((value) => { return !res.has(value[targe]) && res.set(value[targe], 1) } )} console.log(unique(arr, list, "value"));复制代码