Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  120] [ 4]  / answers: 1 / hits: 17156  / 9 Years ago, tue, january 12, 2016, 12:00:00

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


More From » javascript

 Answers
58

Try this



function checkIfNameExists(arr, newName) {
return arr.some(function(e) {
return e.name === 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;
});
}

[#63751] Sunday, January 10, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gageherberth

Total Points: 249
Total Questions: 115
Total Answers: 119

Location: Liechtenstein
Member since Sun, Sep 12, 2021
3 Years ago
;