Home >Web Front-end >JS Tutorial >How to check if an object value exists without adding a new object to the array using 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".
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'));
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.
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)
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!