Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a specific object already exists in an array before adding it

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?

like image 512
olivier Avatar asked Aug 26 '17 12:08

olivier


People also ask

How do you check if an array of objects contains a value?

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 .

How do you check if something exists in an object?

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.


3 Answers

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;
like image 79
Camille Wintz Avatar answered Nov 13 '22 11:11

Camille Wintz


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);
like image 40
JJWesterkamp Avatar answered Nov 13 '22 12:11

JJWesterkamp


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);
like image 32
alexmac Avatar answered Nov 13 '22 12:11

alexmac