The Wayback Machine - https://web.archive.org/web/20240828170753/https://www.geeksforgeeks.org/how-check-if-object-value-exists-not-add-a-new-object-to-array-using-javascript/
Open In App

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

Last Updated : 28 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this tutorial, we need to check whether an object exists within a JavaScript array of objects and if they are not present then we need to add a new object to the array. We can say, every variable is an object, in Javascript. For example, if we have an array of objects like the following.

obj =   { id: 1, name: ''Geeks1" }, 
        { id: 2, name: '"Geeks2"}, 
        { id: 3, name: "Geeks3" }

Approach: We use the some() function method in JavaScript. The some() method is used to check whether any array elements pass a test as provided by callback functions. For empty array elements, this method does not work and this method does not modify the original array.

Syntax:

obj.some(function(value, index)

Example 1: The following code checks whether the object value exists in an array. With the usage of some() function, we check whether each object in the array ‘obj’ contains a property with a specific value i.e it has an id and a name in this case. The “obj.some” takes a function parameter “gfg” and returns “true” if the desired object is found in the array (obj). The checkName() function with the name argument with the value of the object returns a boolean value.

Javascript




var obj = [{ id: 1, name: "Geeks1" },
{ id: 2, name: "Geeks2" },
{ id: 3, name: "Geeks3" }]
 
function checkName(name) {
    return obj.some(function (gfg) {
        return gfg.name === name;
    });
}
 
console.log(checkName('Geeks1'));
console.log(checkName('Geeks4'));


Output:

true
false

Example 2: The following example demonstrates adding an object to the array if it is not present. 

To add a new object, we push a new element in the array using obj.length+1. The length is referred to the property of an object which returns the length of the array. push() method appends the object to the array and adds the element to the end of the object array. We have a function “checkName” through which we pass the name as a parameter and once the name matches that of the object, it returns “true”. In the addObj() function, if any new name is encountered the push() function is used for inserting the element in the subsequent next id.

Javascript




var obj = [{ id: 1, name: "Geeks1" },
{ id: 2, name: "Geeks2" },
{ id: 3, name: "Geeks3" }]
 
function checkName(name) {
    return obj.some(function (gfg) {
        return gfg.name === name;
    });
}
 
function addObj(name) {
    if (checkName(name)) {
        return false;
    }
    obj.push({ id: obj.length + 1, name: name });
    return true;
}
console.log("Adding 'Geeks1' which is not present in the obj")
addObj('Geeks1')
console.log(obj)
console.log("*******************************************")
console.log("Adding 'Geeks4' which is not present in the obj")
addObj('Geeks4')
console.log(obj)


Output:

Adding 'Geeks1' which is not present in the obj
[
      { id: 1, name: 'Geeks1' },
      { id: 2, name: 'Geeks2' },
      { id: 3, name: 'Geeks3' }
]
*******************************************
Adding 'Geeks4' which is not present in the obj
[
      { id: 1, name: 'Geeks1' },
      { id: 2, name: 'Geeks2' },
      { id: 3, name: 'Geeks3' },
      { id: 4, name: 'Geeks4' }
]


Similar Reads

How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
Adding duplicate object keys with different values to another object in an array in JavaScript refers to aggregating values under the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values. Table of Content Using for...of LoopUsing reduce()Using a Map for Multiple ValuesUsing fo
4 min read
How to Check Mentioned File Exists or not using JavaScript/jQuery?
Sometimes we want to upload a file through the path of the file, but a few times the file does not exist. In that case, we have to respond to users the given path does not find any file or does not exist in the mentioned file. Below are the approaches to check if mentioned file exists or not using JavaScript/jQuery: Table of Content Using Ajax() me
3 min read
JavaScript | Add new attribute to JSON object
The task is to add a JSON attribute to the JSON object. To do so, Here are a few of the most used techniques discussed.Example 1: This example adds a prop_11 attribute to the myObj object via var key. C/C++ Code <!DOCTYPE HTML> <html> <head> <title> JavaScript | Add new attribute to JSON object. </title> </head>
2 min read
Happy New Year 2024 | New Year Card Design using HTML CSS and JavaScript
Explore the perfect blend of creativity and technology with our Happy New Year card design tutorial using HTML, CSS, and JavaScript. Read step-by-step guide to craft visually stunning and interactive New Year cards for a memorable celebration. Elevate your web development skills while spreading joy and wishes in style. iframe {width: 100%; height:
7 min read
Add new elements at the beginning of an array using JavaScript
In this article, we will learn how to add new elements at the beginning of an array using JavaScript. We can do this by using the following methods: Table of Content Using the Array unshift() MethodUsing Array splice() MethodUsing the Spread OperatorUsing Array concat() MethodUsing Array.prototype.copyWithin() MethodUsing Array.prototype.reduceRigh
4 min read
How to create a new object from the specified object, where all the keys are in lowercase in JavaScript?
In this article, we will learn how to make a new object from the specified object where all the keys are in lowercase using JavaScript. Example: Here, we have converted the upper case to lower case key values. Input: {RollNo : 1, Mark : 78} Output: {rollno : 1, mark : 78} Approach 1: A simple approach is to Extract keys from Object and LowerCase to
2 min read
How to check whether an object exists in javascript ?
In this article, we will learn how to check whether an object exists in Javascript. An object contains the key-value pair. The object can be used to check if it exists using 2 approaches: Using the typeof operatorUsing a try-catch statement Method 1: Using the typeof operator: The typeof operator returns the type of the variable on which it is call
3 min read
How to Check a Key Exists in JavaScript Object ?
Checking if a key exists in a JavaScript object involves verifying whether a specific property is defined within the object. This practice ensures data integrity, prevents errors, and facilitates smooth program execution by confirming property existence before accessing or manipulating it. Objects in JavaScript are non-primitive data types that hol
3 min read
JavaScript Check if a key exists inside a JSON object
To determine whether a specific key exists within a JSON object in JavaScript , you need to verify the presence of that key within the object's structure. This check is crucial when working with dynamic or external data, ensuring your code handles objects correctly by confirming the existence of required keys before accessing their values. Below ar
4 min read
How to check if the provided value is an object created by the Object constructor in JavaScript ?
In this article, we will learn how to check if the provided value is an object created by the Object constructor in JavaScript. Almost all the values in JavaScript are objects except primitive values. There are several methods that can be used to check if the provided value is an object created by the Object constructor in JavaScript. Using the ins
3 min read
How to check an element is exists in array or not in PHP ?
An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods : Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP is used to check the presence of an element in the
2 min read
Check if Pair with given Sum Exists in Array using JavaScript
We will check if a pair with a given Sum exists in an Array or not using JavaScript. 2Sum ProblemThe 2sum is a famous problem asked in most interviews. We have to check whether a pair of numbers exists whose sum is equal to the target value. We are given an array of integers and the target value. We have to return true if the pair whose sum is equa
4 min read
Remove & Add new HTML Tags using JavaScript
In web development, dynamically add or remove HTML tags using JavaScript. This can be useful for creating interactive user interfaces and updating content based on user actions. Below are the approaches to remove and add new HTML tags using JavaScript: Table of Content Using createElement and removeChildUsing innerHTMLUsing createElement and remove
3 min read
How to check element exists or not in jQuery ?
Checking if an element exists in jQuery involves selecting the element and verifying its length. If the selected element's length is greater than 0, the element exists in the DOM; otherwise, it doesn't. This is useful for conditionally manipulating elements. There are two ways to check whether an element in the HTML document exists or not using jQu
3 min read
How to check whether an array includes a particular value or not in JavaScript ?
In this article, we will discuss the construction of an array followed by checking whether any particular value which is required by the user is included (or present) in the array or not. But let us first see how we could create an array in JavaScript using the following syntax- Syntax: The following syntax would be helpful for any user for the cre
3 min read
How to add Key-Value pair to a JavaScript Object?
JavaScript object has key-value pair and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods. Below are the methods to add a key/value pair to a JavaScript object: Table of Content Using Dot NotationUsing Bracket NotationUsing Spread OperatorUsing Objcet.assign() M
3 min read
JavaScript for...in loop not working - Object property is not defined Error
A for...in loop is a special loop in JavaScript that enumerates all the keys (object property names) of an object. With each new iteration, a new property string is assigned to the loop variable. Error: Uncaught ReferenceError: Object property is not defined If we try to compare this loop variable with a non-string variable a ReferenceError is gene
3 min read
Check if Pair with Given Sum Exists in Array in JavaScript
Two Sum is a classic algorithmic problem where you're given an array of integers and a target sum. The task is to determine whether any two numbers in the array add up to the target sum. Given an array A[] of n numbers and another number x, the task is to check whether or not there exist two elements in A[] whose sum is exactly x. Examples: Input:
3 min read
How to Check if an Element Exists in an Array in JavaScript ?
In JavaScript, you can check if an element exists in an array using various methods, such as indexOf(), includes(), find(), some(), or Array.prototype.findIndex(). Here's how you can achieve it using these methods: Table of Content Using indexOf() methodUsing includes() methodUsing find() methodUsing some() methodUsing Array.prototype.findIndex() m
3 min read
How to check an Array Contains an Object of Attribute with Given Value in JavaScript ?
Sometimes, when working with an array of objects in JavaScript, we need to determine whether an object with a specific attribute value exists in the array. This can be useful when filtering or searching for specific objects in the array. Below are the common methods to determine if the array contains an object with an attribute. Table of Content Us
4 min read
How to extend an existing array with another array without creating a new array in JavaScript ?
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It's easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array. There are two easy w
2 min read
New self vs. new static in PHP
New self: The self is keyword in PHP. It refers to the same class in which the new keyword is actually written. It refers to the class members, but not for any particular object. This is because the static members(variables or functions) are class members shared by all the objects of the class. The function called self::theFunction() behaves like "
4 min read
How to Check an Element with Specific ID Exists using JavaScript ?
Given an HTML document containing some elements and the elements contain some id attribute. The task is to check whether the element with a specific ID exists or not using JavaScript. Below are the approaches to check an element with specific ID exists or not using JavaScript:  Table of Content Approach 1: Using the document.getElementById() method
3 min read
How to Add a new Element to HTML DOM in JavaScript ?
Adding a new element to the HTML DOM dynamically using JavaScript is a common requirement in web development. This allows developers to create interactive and dynamic web pages without the need to reload the entire page. There are several approaches to adding a new element to HTML DOM in JavaScript which are as follows: Table of Content Using creat
2 min read
How to Append an Object as a Key Value in an Existing Object in JavaScript ?
In JavaScript, An object is a key-value pair structure. The key represents the property of the object and the value represents the associated value of the property. In JavaScript objects, we can also append a new object as a Key-value pair in an existing object in various ways which are as follows. Table of Content Using JavaScript Spread (...) Ope
3 min read
How to Search Character in List of Array Object Inside an Array Object in JavaScript ?
Searching for a character in a list of array objects inside an array object involves inspecting each array object, and then examining each array within for the presence of the specified character. The goal is to determine if the character exists within any of the nested arrays. There are several ways to search for characters in a list of array obje
4 min read
How to Add Apple's new San Francisco font on a Webpage using CSS ?
The newly created Apple's San Francisco font is comfortable for human eyes as per research. Normally Apple's font can not be used on any webpage through CSS. These kind of fonts are in-build in Apple's product but the new San Francisco font can be used in any web content. Mr. Craig Hockenberry introduces the procedure of how we can use that font on
2 min read
How to add a new class to an element that already has a class using jQuery ?
In this article, we will learn to add a new class to an element that already has a class using jQuery. There are different methods of achieving this task using the built-in methods available in jQuery. The approaches we can use to add a class to an element using jQuery are listed below: Table of Content Using the addClass() methodUsing the attr() m
3 min read
Object.create vs. New in JavaScript
The new keyword and Object.create() are frequently used to instantiate objects in JavaScript but they have distinct characteristics and use cases. Understanding the differences between new and Object.create() is essential for mastering object creation in JavaScript. What is new?The new keyword in JavaScript is primarily used with the constructor fu
2 min read
How to check if the value is primitive or not in JavaScript ?
To check if the value is primitive we have to compare the value data type. As Object is the non-primitive data type in JavaScript we can compare the value type to object and get the required results. Primitive data types are basic building blocks like numbers and characters, while non-primitive data types, such as arrays and objects, are more compl
3 min read