两个json 去重

小丑的帽子
  • 101

a = [{ "id": "1231" }, { "id": "9387" }, { "id": "68433" }, { "id": "43566" }]
b = [{ "id": "1231" }, { "id": "43566" }]
预期结果为 c = [{ "id": "9387" }, { "id": "68433" }]

求教大神

回复
阅读 2.3k
5 个回答
✓ 已被采纳

我写了一个方法,用到了ES6,你直接复制执行便可看到效果,希望能帮助到你:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>tab</title>
</head>
<body>
    <script>
        let a = [{
            "id": "1231"
        }, {
            "id": "9387"
        }, {
            "id": "68433"
        }, {
            "id": "43566"
        }];
        let b = [{
            "id": "1231"
        }, {
            "id": "43566"
        }];
        let c = a.filter((value) => {
            for (let k in b) {
                if (value.id === b[k].id) {
                    return false;
                }
            }
            return value;
        });
        console.log(c);
    </script>
</body>
</html>
var a = [{ "id": "1231" }, { "id": "9387" }, { "id": "68433" }, { "id": "43566" }],
b = [{ "id": "1231" }, { "id": "43566" }],
c = a.filter(function(o) {
  return b.every(function(e){
    return o.id !== e.id;
  });
});
alert(JSON.stringify(c));

提供一个思路,把两个数组连接成一个数组,然后就是对数组的去重了。

let a = [{ "id": "1231" }, { "id": "9387" }, { "id": "68433" }, { "id": "43566" }]
let b = [{ "id": "1231" }, { "id": "43566" }]

let obj = [...a, ...b].reduce((obj, val) => {
  let str = JSON.stringify(val)
  obj[str] = obj[str] ? ++obj[str] : 1
  return obj
}, {})

let c = Object.keys(obj).filter(key => obj[key] === 1)

如果题主去重是要把相同的从两边都删掉,以多的为准的话,就是下面这样:如果 key 可能为 对象的话,还需要做JSON.stringify 处理,有问题留言

let a = [{ "id": "1231" }, { "id": "9387" }, { "id": "68433" }, { "id": "43566" }];
let b = [{ "id": "1231" }, { "id": "43566" }];


function uniqueArr(arrA, arrB, key) {
    let bigArr = arrA.length > arrB.length ? arrA : arrB,
        smallArr = arrA.length <= arrB.length ? arrA : arrB;
    smallArrData = smallArr.map((obj, index) => obj[key]);
    return bigArr.filter((obj, index) => smallArrData.indexOf(obj[key]) === -1);
}

console.log(uniqueArr(a, b));

@luozz 图片描述

麻烦你看下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏