数组对象push时去重

Lewis
2022-08-23 / 0 评论 / 10 阅读 / 正在检测是否收录...

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));

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"}]
0

评论 (0)

取消