Home  >  Article  >  Web Front-end  >  How to check if an object value exists without adding a new object to the array using JavaScript?

How to check if an object value exists without adding a new object to the array using JavaScript?

WBOY
WBOYforward
2023-09-08 10:49:02942browse

如何使用 JavaScript 检查对象值是否存在而不向数组添加新对象?

In this article, you will learn how to check if an object value exists and if not, add a new object to an array using JavaScript. In Javascript, almost every variable is an object. Objects can be strings, numbers, Boolean values, etc., or key-value pairs.

An array in JavaScript is a special type of variable that can hold multiple items. Arrays can be initialized using the keyword "const".

Example 1

In this example, we use the .some() function to check whether the object exists.

var inputArray = [{ id: 1, name: "JavaScript" },
   { id: 2, name: "javascript"},
   { id: 3, name: "Scala" },
   { id: 4, name: "Java" }]
console.log("The input array is defined as: ")
console.log(inputArray)
function checkName(name) {
   return inputArray.some(function(check) {
      return check.name === name;
   });
}
console.log("Does the object JavaScript exist in the array? ")
console.log(checkName('JavaScript'));
console.log("Does the object HTML exist in the array? ")
console.log(checkName('HTML'));

illustrate

  • Step 1 - Define an array "inputArray" and add key-value pairs to it.

  • Step 2 - Define a function "checkName" which takes a string as parameter.

  • Step 3 - In the function, use the function some() to check if the given value exists in the array.

  • Step 4 - Display a Boolean value as the result.

Example 2

In this example, we add the object value to the array by pushing the object to the end of the array using the push() function.

var inputArray = [{ id: 1, name: "JavaScript" },
{ id: 2, name: "javascript"},
{ id: 3, name: "Scala" }]
console.log("The input array is defined as: ")
console.log(inputArray)
function addObject(name) {
   inputArray.push({ id: inputArray.length + 1, name: name });
   return true;
}
console.log("Adding Object : Java to the array")
addObject("Java")
console.log("The array after adding the object is")
console.log(inputArray)

illustrate

  • Step 1 - Define an array "inputArray" and add key-value pairs to it.

  • Step 2 - Define a function "addObject" which takes a string as parameter.

  • Step 3 - In the function, use the function array.push to push the object to the last position of the array.

  • Step 4 - Display the array as the result.

The above is the detailed content of How to check if an object value exists without adding a new object to the array using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete