Javascript array.include是否在嵌套对象上工作
这是我的数组的一个示例对象,我是否能够使用array.includes检测数组中是否已存在此对象。这是我的检查。我的目标是不推送重复的元素Javascript array.include是否在嵌套对象上工作,javascript,arrays,node.js,nested-object,Javascript,Arrays,Node.js,Nested Object,这是我的数组的一个示例对象,我是否能够使用array.includes检测数组中是否已存在此对象。这是我的检查。我的目标是不推送重复的元素 { "identityA": { "_id": "5e98baf27457da339b219eb8", "altitude": 0, "startTime": "2020-04-16T20:07:00.000Z", "endTime": "2020-04-16T20:07:00.000Z",
{
"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.prototype.includes本质上与=
操作符进行比较的方式相同。因此,对于对象,它通过引用进行比较,而不是通过值进行比较
这就是为什么使用引用调用包含将起作用,而使用具有相同属性值但不是引用的对象调用包含将不起作用:
const arr=[
{
名称:“object1”
},
{
名称:“object2”
}
];
console.log(arr.includes(arr[0]);/>真的
log(arr.includes({name:'object1'}));//-->false
您需要将.find()
与对象的id
if (!finalInteractions.includes(element1)) {
finalInteractions.push(element1);
}