How do I check if a value exists in an array of objects in JavaScript?
Richard W
richard w profile pic

In JavaScript, you can check if a value exists in an array of objects by iterating through the array and comparing the desired value against each object's properties. Here's an example of how you can accomplish this:

1
2
3
4
5
6
7
8
9
10
11
12

function checkValueExists(array, value) {
  for (let i = 0; i < array.length; i++) {
    const obj = array[i];
    for (let key in obj) {
      if (obj.hasOwnProperty(key) && obj[key] === value) {
        return true;
      }
    }
  }
  return false;
}

In this example, thecheckValueExists function takes two parameters: thearray to search in and thevalue to look for. It uses nested loops to iterate through the array and each object's properties. For each object in the array, the inner loop checks if the object has the current property (obj.hasOwnProperty(key)) and if the value of that property matches the desired value (obj[key] === value). If a match is found, the function returnstrue immediately, indicating that the value exists in the array. If the entire array has been iterated without finding a match, the function returnsfalse, indicating that the value does not exist in the array. Here's an example usage of thecheckValueExists function:

1
2
3
4
5
6
7
8
9

const array = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 40 }
];

console.log(checkValueExists(array, 'Jane')); // Output: true
console.log(checkValueExists(array, 'Alice')); // Output: false

In this example, thecheckValueExists function is used to check if the value'Jane' exists in thename property of any object in thearray. The function returnstrue because the value'Jane' is found in thename property of the second object in the array. Keep in mind that this implementation checks for equality (===) and works for primitive values. If you want to check for the existence of an object in the array based on its reference, you can use the=== operator directly without iterating through the array. If you need more advanced or specific matching criteria, you may need to customize the function accordingly, considering the structure and properties of your objects.