push数组对象怎么去重

image.png
arr数组里全是这种对象,怎么去重,只保留push进去的最新的
我写好了一部分image.png这里image.png
该怎么写?

阅读 3.1k
2 个回答

去重得先判重,这种结构复杂,但是值简单的,可以用 Lodash 的 isEquals() 来判断是否相同对象。

如果 整个对象作为判断条件可以这样做

var arr = [{id: '1', name: 'abc'}, {id: '3', name: 'abc'}];
var obj = {id: '2', name: 'abc'};
if (!JSON.stringify(arr).includes(JSON.stringify(obj))) {
    arr.push(obj);
}
console.log(JSON.stringify(arr));
// [{"id":"1","name":"abc"},{"id":"3","name":"abc"},{"id":"2","name":"abc"}]

根据id判断

var arr = [{match_id: '1', name: 'abc'}, {match_id: '3', name: 'abc'}];
    var obj = {match_id: '2', name: 'abc'};

    var map = arr.map(item=>({[item.match_id]: item}));
    if(map[obj.match_id]){
        map[obj.match_id] = obj;// 更新对象
        arr = Object.values(map); // map 转 arr
    } else {
        arr.push(obj);
    }
    console.log(JSON.stringify(arr));
    // [{"match_id":"1","name":"abc"},{"match_id":"3","name":"abc"},{"match_id":"2","name":"abc"}]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题