javascript - array.include 是否适用于嵌套对象
问题描述
{
"identityA": {
"_id": "5e98baf27457da339b219eb8",
"altitude": 0,
"startTime": "2020-04-16T20:07:00.000Z",
"endTime": "2020-04-16T20:07:00.000Z",
"lat": 30.66702,
"lng": 73.12998,
"personId": "5e95dfc46cbdd81757e47da2"
},
"identityB": {
"_id": "5e98baf47457da339b219eba",
"altitude": 0,
"startTime": "2020-04-16T20:07:00.000Z",
"endTime": "2020-04-16T20:07:00.000Z",
"lat": 30.66869,
"lng": 73.13591,
"personId": "5e97682d517976252cdab2d1"
},
"dist": 0.3709439708757079,
"id": "5e98bbb77457da339b219ed6",
"createdAt": "2020-04-16T20:10:31.314Z",
"updatedAt": "2020-04-16T20:10:31.314Z"
}
这是我的数组的一个示例对象,我能否使用 array.includes 检测我是否已经在数组中有这个对象。这是我的检查。我的目标是不推送重复的元素
if (!finalInteractions.includes(element1)) {
finalInteractions.push(element1);
}
解决方案
Array.prototype.includes
本质上===
比较运算符的方式相同。所以对于对象,它通过引用而不是值进行比较。
这就是为什么includes
使用引用调用将起作用,而includes
使用具有相同属性值但不是引用的对象调用将不起作用:
const arr = [
{
name: 'object1'
},
{
name: 'object2'
}
];
console.log(arr.includes(arr[0])); // --> true
console.log(arr.includes({name: 'object1'})); // --> false
推荐阅读
- authentication - 无法登录mailgun帐户。“CSRF 会话令牌丢失。”
- amazon-web-services - 如何在 ELB 应用程序上配置 HTTPS?
- magento - Magento:在管理员中获取客户 ID
- java - 如何让 Java 声音 API 从 jar 中工作
- css - 我不能使用@font-face
- jquery - 我使用猫头鹰旋转木马,在移动视图中我只想显示单个项目。但是当我单击下一个按钮时,第二个项目从左侧剪切
- python - django:上传的图片不会显示
- python - How to fill up a matrix in Python using for loops
- c# - 从具有特定模式的文本文件中读取文本
- arrays - 在 Spark 数据框中过滤 json 数组数据