Skip to content

JavaScript checks if the value exists in an array of objects | Example code

  • by

Use some function to check if the value exists in an array of objects in JavaScript. some is a great function for checking the existence of things in arrays:

JavaScript check if a value exists in an array of objects

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    const arr = [{ id: 1, username: 'fred' }, 
    { id: 2, username: 'bill' }, 
    { id: 3, username: 'ted' }];

    const found = arr.some(el => el.username === 'ted');

    console.log('ted found',found);

  </script>

</body>
</html> 

Output:

JavaScript checks if the value exists in an array of objects

Add value if not exists

Loop through the array to check whether a particular username value already exists and if it does do nothing, but if it doesn’t add a new object to the array.

const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];

function add(arr, name) {
  const { length } = arr;
  const id = length + 1;
  const found = arr.some(el => el.username === name);
  if (!found) arr.push({ id, username: name });
  return arr;
}

console.log(add(arr, 'ted'));

Source: stackoverflow.com

Check if one element exists in an array of objects

var memberships = [{
    id: 1,
    type: 'guest'
  },
  {
    id: 2,
    type: 'member'
  }
];

var status = memberships.some(function(el) {
  return (el.type == 'member');
});
console.log(status);

Do comment if you have any doubts or suggestions on this JS Array of object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *