How Check if object value exists not add a new object to array using JavaScript ?


In this article, you will understand how to check if the object value exists, if not, add a new object to the array using JavaScript. In Javascript, almost every variable is an object. An object can be a string, numbers, boolean values, etc. They can also be key-value pairs.

An array in javascript is a special variable that can hold more than one item. An array can be initialized using the keyword ‘const’.

Example 1

In this example, we check the existence of the object using the .some() function.

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'));

Explanation

  • Step 1 −Define an array ‘inputArray’ and add key value pair values to it.

  • Step 2 −Define a function ‘checkName’ that takes a string as a parameter.

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

  • Step 4 −Display the boolean value as result.

Example 2

In this example, we add the object value to the array by pushing the object at the end of the array using 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)

Explanation

  • Step 1 −Define an array ‘inputArray’ and add key value pair values to it.

  • Step 2 −Define a function ‘addObject’ that takes a string as a 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 result.

Updated on: 16-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements