如何在添加特定对象之前检查其是否已存在于数组中 [英] How to check if a specific object already exists in an array before adding it
本文介绍了如何在添加特定对象之前检查其是否已存在于数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组:
[{"name": "Olvier", "id": 123 }, {"name": "Olvier", "id": 124 }]
现在我的目标是防止将相同的对象再次添加到数组中:
Now my goal is to prevent adding the same object again to the array:
{"name": "Olvier", "id": 123 }
是否有一种方法可以做到这一点?
Is there a Method to do this?
推荐答案
如果对象创建得较早,并且与数组中的对象具有相同的引用,则可以使用indexOf:
If your object is created earlier and has the same reference as the one in the array, you can use indexOf:
var myObj = { a: 'b' };
myArray.push(myObj);
var isInArray = myArray.indexOf(myObj) !== -1;
否则,您可以使用以下命令进行检查:
Otherwise you can check it with find:
var isInArray = myArray.find(function(el){ return el.id === '123' }) !== undefined;
这篇关于如何在添加特定对象之前检查其是否已存在于数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文