javascript - array.include 是否适用于嵌套对象

标签 javascript arrays node.js nested-object

    {
    "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

关于javascript - array.include 是否适用于嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61326797/

相关文章:

python - 从 numpy 数组中获取第 n 个元素

node.js - 使用 Bluebird 将所有 csv 文件读入 Node js 中的 1 个 JSON 对象数组

javascript - 使用我网站上的按钮更改 h1/h2/h3 的字体大小(使用本地存储)

javascript - Node + Mysql - 连接问题

python - 从 sqlite 查询中删除格式

javascript - React 中具有固定记录数的多行

javascript - Sequelize include 不适用于 hasOne 关系

node.js - Node 服务器监听公网IP失败

javascript - 如何在同一页面上复制 [播放] 和 [暂停] 按钮进行音频播放?

javascript - Rally 列出所有功能查询