JavaScript中最好的方法是遍历对象数组并检查数组对象的某个属性中是否已存在某个值? 例如:我有以下对象数组: [{name:team1,members:3},{name:bestteam,members:4}] 现在我想要添加一个新对象,但我想在添加它之前检查数组中是否存在此对象属性name
What is the best way in JavaScript to go over array of object and check if an certain value already exist in one of the property of the array objects? For example: I have array of objects as follow: [{name:"team1",members:3},{name:"bestteam",members:4}] Now I want to add a new object but I want to check that this object property "name" do not exist in the array before adding it
推荐答案试试这个
function checkIfNameExists(arr, newName) { return arr.some(function(e) { return e.name === newName; }); }其中arr是你的数组,newName是要检查的名字。
where arr is your array and newName is the name to check.
您还可以通过将属性作为参数传递给比较来减少临时性,例如
You could also make it less ad hoc by passing the property to compare as a parameter, like so
function checkIfNameExists(arr, prop, newVal) { return arr.some(function(e) { return e[prop] ? e[prop] === newVal : false; }); }更多推荐
在对象数组中查找重复值
发布评论