I have an array of objects, and want to add a new object only if that object doesn't already exist in the array. The objects in the array have 2 properties, name and imageURL and 2 objects are same only if their name is same, and thus I wish to compare only the name to check whether the object exists or not How to implement this as a condition??
Since you've not mentioned the variables used. I'll assume 'arr' as the array and 'person' as the new object to be checked.
const arr = [{name: 'John', imageURL:'abc.com'},{name: 'Mike', imageURL:'xyz.com'}];
const person = {name: 'Jake', imageURL: 'hey.com'};
if (!arr.find(
element =>
element.name == person.name)
) {
arr.push(person);
};
If the names are not same, the person object won't be pushed into the array.