我只需要得到两个数组之间的差异
我试过了:
let arr1 = {
"data": [{
"id": "EID_Floss",
"name": "Floss",
"te": "dd"
}]
}
let arr2 = {
"data": [{
"id": "EID_Floss",
"name": "Floss"
}]
}
JSON.stringify(arr2.data.filter((x) => !arr1.data.includes(x)))
结果:
[{
"id": "EID_Floss",
"name": "Floss"
}]
如何获得:
[{
"te": "dd"
}]
答案 0 :(得分:1)
看看这个更简单的例子:
arr1 = ["foo", "bar"];
arr2 = ["foo", "bar", "foobar"];
arr3 = arr2.filter((x) => !arr1.includes(x));
console.log(arr3);
这正是你所期望的,输出是:
<块引用>["foobar"]
您的示例的问题在于 arr1 = ["foo", "bar"];
arr2 = ["foo", "bar", "foobar"];
arr3 = arr2.filter((x) => !arr1.includes(x));
console.log(arr3);
和 arr1.data
中的数组包含对象。您正在比较对象
arr2.data
来自 {
"id": "EID_Floss",
"name": "Floss",
"te": "dd"
}
的对象
arr1
来自{
"id": "EID_Floss",
"name": "Floss"
}
。由于这些不相等,您的过滤器不会从数组中删除对象。
请注意,这是一个全有或全无操作,因为您正在过滤对象数组。相反,听起来您想要过滤每个对象中的键。因此您需要使用 arr2
或 Object.keys()
来迭代对象的内容。