I have this array:
[{"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?
Checking if Array of Objects Includes Object We can use the some() method to search by object's contents. The some() method takes one argument accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .
Use the in operator The in operator returns true if a property exists in an object. If a property does not exist in the object, it returns false . Unlike the hasOwnProperty() method, the in operator looks for the property in both own properties and inherited properties of the object.
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;
If the id's are unique you can simply check if an object with a certain id exists:
const collection = [
{"name": "Olvier", "id": 123 },
{"name": "Olvier", "id": 124 }
];
let person = { "name": "Olvier", "id": 123 };
function addPerson(person) {
const existingIds = collection.map((addedPerson) => addedPerson.id);
if (! existingIds.includes(person.id)) {
collection.push(person);
}
}
addPerson(person);
You could use Array#some method to determinate that item is already in array or not:
var arr = [
{ name: 'Olvier', id: 123 },
{ name: 'Olvier', id: 124 }
];
var existingItem = arr[1];
var newItem = { name: 'John', id: 125 };
if (!arr.some(item => item === existingItem)) {
arr.push(existingItem);
}
console.log(arr);
if (!arr.some(item => item === newItem)) {
arr.push(newItem);
}
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With