# js对象数组去重
# 方法一
采用对象访问属性的方法,判断属性值是否存在,如果不存在就添加。
var arr = [{
key: '01',
value: '乐乐'
}, {
key: '02',
value: '博博'
}, {
key: '03',
value: '淘淘'
},{
key: '04',
value: '哈哈'
},{
key: '01',
value: '乐乐'
}];
// 方法1:利用对象访问属性的方法,判断对象中是否存在key
var result = [];
var obj = {};
for(var i =0; i</div></div></div><p data-lake-id="0a731ff72781dad753a15553b756fe90" style="font-size: 14px; color: rgb(38, 38, 38); line-height: 1.74; letter-spacing: 0.05em; outline-style: none; overflow-wrap: break-word; margin: 0px;"><br></p>
## 方法二
<p data-lake-id="904b9ab157fb7c0aed2df6d231b75e2b" style="font-size: 14px; color: rgb(38, 38, 38); line-height: 1.74; letter-spacing: 0.05em; outline-style: none; overflow-wrap: break-word; margin: 0px;"><br></p><p data-lake-id="352aa51791413573fcd127235ba934a8" style="font-size: 14px; color: rgb(38, 38, 38); line-height: 1.74; letter-spacing: 0.05em; outline-style: none; overflow-wrap: break-word; margin: 0px;"><strong>采用数组中的reduce方法,遍历数组,也是通过对象访问属性的方法。</strong></p><p data-lake-id="17e1c1afe6fa5a80fd7f08d437a8374e" style="font-size: 14px; color: rgb(38, 38, 38); line-height: 1.74; letter-spacing: 0.05em; outline-style: none; overflow-wrap: break-word; margin: 0px;"><br></p><div data-card-type="block" data-lake-card="codeblock" id="6b84d9ca" data-language="javascript"><div class="lake-codeblock-content" style="border: 1px solid rgb(232, 232, 232); max-width: 750px; color: rgb(89, 89, 89); margin: 0px; padding: 0px; background: rgb(249, 249, 249);"><div class style="color: rgb(89, 89, 89); margin: 0px; padding: 16px; background: none 0% 0% / auto repeat scroll padding-box border-box rgba(0, 0, 0, 0);">
``` undefined
// 方法2:利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数,第二个参数是item的初始值
var obj = {};
arr = arr.reduce(function(item, next) {
obj[next.key] ? '' : obj[next.key] = true && item.push(next);
return item;
}, []);
console.log(arr); // [{key: "01", value: "乐乐"},{key: "02", value: "博博"},{key: "03", value: "淘淘"},{key: "04", value: "哈哈"}]
参考链接: