check if array contains object with id js in javascript

To check if an array contains an object with a specific id property in JavaScript, you can use the Array.some() method along with a callback function. Here's an example:

index.tsx
function arrayContainsObjectWithId(arr, id) {
  return arr.some(obj => obj.id === id);
}

// Example usage
const array = [
  { id: 1, name: 'Object 1' },
  { id: 2, name: 'Object 2' },
  { id: 3, name: 'Object 3' }
];

console.log(arrayContainsObjectWithId(array, 2)); // Output: true
console.log(arrayContainsObjectWithId(array, 4)); // Output: false
352 chars
14 lines

In the above code, the arrayContainsObjectWithId function takes an array (arr) and an id as arguments. It uses the Array.some() method to iterate over each object in the array and checks if any object's id property matches the provided id. If at least one object satisfies the condition, it returns true, otherwise false.

related categories

gistlibby LogSnag