Reputation: 167
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??
Upvotes: 0
Views: 55
Reputation: 47
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.
Upvotes: 1
Reputation: 3820
You can use Array.find
let newObj={ name:'X',imageURL:'..../'}
if(!array.find(x=> x.name == newObj.name))
array.push(newObj)
Upvotes: 1
Reputation: 674
You need to check it using find
or similar functions like this:
const arr = [{ name: 1 }, { name: 2 }];
function append(arr, newEl) {
if (!arr.find(el => el.name == newEl.name)) {
arr.push(newEl);
}
}
append(arr, { name: 2 }); // won't be added
console.log(arr);
append(arr, { name: 3 }); // will be added
console.log(arr);
Upvotes: 0