In this post, we will discuss how to find an object by its ID in an array of JavaScript objects. I have an array of objects containing a list of named objects, and I need to retrieve the object where the 'id' is '2'.

Below is an example array

var customerarray =
            [
                { 'id': '1', 'name': 'Shelley Burke', 'address': 'P.O. Box 78934', 'country': 'Norway' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '3', 'name': 'Ian Devling', 'address': 'Av. das Americanas 12.890', 'country': 'Sweden' },
                { 'id': '4', 'name': 'Peter Wilson', 'address': 'Tiergartenstraße 5', 'country': 'Germany' },
                { 'id': '5', 'name': 'Sven Petersen', 'address': 'Frahmredder 112a', 'country': 'UK' },
                { 'id': '6', 'name': 'Hatlevegen 5', 'address': '3400 - 8th Avenue Suite 210', 'country': 'USA' },
                { 'id': '7', 'name': 'Marry 5', 'address': 'Brovallavägen ', 'country': 'Sweden' },
            ]

As you can see above array, we have an array of the customer object which has id, name, address, and country property. Now let’s say, I want to be able to search customerarrayobj for an object with an “id” matching for example with id=”2″.

the easiest way to do this task is using the find() function, but let you know that it won’t work on Internet Explorer 8 or earlier.

Let me explain to you,The find() function by default returns the first element in the array if an element in the array object match the provided condition,Otherwise find() function return undefined.

Method 1: Find object by id in an array of JavaScript objects

<script type="text/javascript">
//I think the easiest way would be the following, but it won't work on Internet Explorer 8 (or earlier):
var customerarrayobj =
            [
                { 'id': '1', 'name': 'Shelley Burke', 'address': 'P.O. Box 78934', 'country': 'Norway' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '3', 'name': 'Ian Devling', 'address': 'Av. das Americanas 12.890', 'country': 'Sweden' },
                { 'id': '4', 'name': 'Peter Wilson', 'address': 'Tiergartenstraße 5', 'country': 'Germany' },
                { 'id': '5', 'name': 'Sven Petersen', 'address': 'Frahmredder 112a', 'country': 'UK' },
                { 'id': '6', 'name': 'Hatlevegen 5', 'address': '3400 - 8th Avenue Suite 210', 'country': 'USA' },
                { 'id': '7', 'name': 'Marry 5', 'address': 'Brovallavägen ', 'country': 'Sweden' },
            ]

        
const result = customerarrayobj.find(x => x.id === '2');
if (result)//check if result is not undefined in case if record not find the array object
        {
            document.write("Result found in the array with id:" + result.id +
"<br><br> customer name:" + result.name +
" <br>address:" + result.address +
"<br>country:" + result.country+"<br>");
        }
    </script>

Once that object is found in the array, we get the information from the object and write it in the document.

  • Find a specific customer object from an array based on its ID and then display its details. 
  • An array of customer objects called customerarrayobj is defined. Each object in the array represents a customer and contains properties such as 'id', 'name', 'address', and 'country'.
  • A variable named result is declared and assigned the result of the customerarrayobj.find() method. This method searches the array for the first element that satisfies the provided testing function. In this case, it looks for an object whose 'id' property matches '2'.
  • There's a conditional statement if (result) to check if the result is not undefined. This check ensures that if the customer with the specified ID is not found in the array, the subsequent code block is not executed.
  • If result is not undefined, the details of the customer object are displayed using document.write(). The details include the customer's ID, name, address, and country. The information is concatenated into a string and written onto the document.

get array by value

Find a value in an array of objects in Javascript

Let's consider a real-time example of finding a value in an array of objects in JavaScript. I've created an HTML page with a text input where users can input an ID. Based on this ID, I'll search for the corresponding object in the array by its ID. Then, I'll display that object in a div.

The code defines an array called customerarrayobj, which contains several objects representing customers. Each object has properties such as 'id', 'name', 'address', and 'country'.

A function named Filterarray() is defined. This function is intended to be called when a user interacts with an input field (presumably with an id of "txtinput"), typically when they enter an ID and trigger an event like clicking a button or pressing Enter.

Inside the Filterarray() function, it retrieves the value entered by the user into the input field with the id "txtinput".

There's a conditional statement if (id) to check if the entered ID is not empty or undefined.

If the entered ID is not empty, the code searches for a customer object in the customerarrayobj array whose 'id' property matches the entered ID using the find() method.

There's another conditional statement if (result) to check if the result is not undefined. This check ensures that if the customer with the specified ID is not found in the array, the subsequent code block is not executed.

If result is not undefined, the details of the customer object are displayed in an HTML element with the id "divresult". The details include the customer's ID, name, address, and country. The information is concatenated into a string and set as the inner HTML of the specified element.

Overall, below code allows users to enter a customer ID, and upon submission, it searches for the corresponding customer in the array and displays their details dynamically on the webpage.

 

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <input type="number" id="txtinput" onchange="Filterarray()"/>
    <div id="divresult"></div>
    <script type="text/javascript">
//I think the easiest way would be the following, but it won't work on Internet Explorer 8 (or earlier):
var customerarrayobj =
            [
                { 'id': '1', 'name': 'Shelley Burke', 'address': 'P.O. Box 78934', 'country': 'Norway' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '3', 'name': 'Ian Devling', 'address': 'Av. das Americanas 12.890', 'country': 'Sweden' },
                { 'id': '4', 'name': 'Peter Wilson', 'address': 'Tiergartenstraße 5', 'country': 'Germany' },
                { 'id': '5', 'name': 'Sven Petersen', 'address': 'Frahmredder 112a', 'country': 'UK' },
                { 'id': '6', 'name': 'Hatlevegen 5', 'address': '3400 - 8th Avenue Suite 210', 'country': 'USA' },
                { 'id': '7', 'name': 'Marry 5', 'address': 'Brovallavägen ', 'country': 'Sweden' },
            ]

        function Filterarray()
        {
var id = document.getElementById("txtinput").value;
if (id)
            {
const result = customerarrayobj.find(x => x.id === id);
if (result)//check if result is not undefined in case if record not find the array object
                {
                    document.getElementById("divresult").innerHTML = "Result found in the array with id:" + result.id +
"<br><br> customer name:" + result.name +
" <br>address:" + result.address +
"<br>country:" + result.country + "<br>";
                }
            }
           
        }
        
    </script>
</body>
</html>

searchtextbox

Method 2: Get JavaScript object from array of objects by value of property using loop

Here we are Iterating over any object in the array. For every object, we are, checking that object’s id. it’s a match, then return that object.

A function named SearchElementById() is defined, which takes two parameters: arrayobject (the array to search in) and id (the ID to search for).

Inside the SearchElementById() function, a for loop iterates over each item in the array. For each item, it checks if the 'id' property matches the provided ID. If a match is found, the corresponding object is returned.

If no match is found after iterating through the entire array, the function returns null to indicate that no element with the specified ID was found.

Outside the function, the SearchElementById() function is called with the ArrayOfCustomer array and the ID '6'. This searches for a customer object with the ID '6'.

If a customer object is found (i.e., customerObj is not null), its details are displayed using document.write(). The details include the customer's ID, name, address, and country. The information is concatenated into a string and written onto the document.

A basic approach to searching for an element in an array of objects using a custom JavaScript function and iterating through the array to find a match.


<script type="text/javascript">
var ArrayOfCustomer =
            [
                { 'id': '1', 'name': 'Shelley Burke', 'address': 'P.O. Box 78934', 'country': 'Norway' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '3', 'name': 'Ian Devling', 'address': 'Av. das Americanas 12.890', 'country': 'Sweden' },
                { 'id': '4', 'name': 'Peter Wilson', 'address': 'Tiergartenstraße 5', 'country': 'Germany' },
                { 'id': '5', 'name': 'Sven Petersen', 'address': 'Frahmredder 112a', 'country': 'UK' },
                { 'id': '6', 'name': 'Hatlevegen 5', 'address': '3400 - 8th Avenue Suite 210', 'country': 'USA' },
                { 'id': '7', 'name': 'Marry 5', 'address': 'Brovallavägen ', 'country': 'Sweden' },
            ]
//Here we Iterate over any item in the array.For each item in the array, check that item's id match or not
        function SearchElementById(arrayobject, id) {
for (var i = 0, len = arrayobject.length; i < len; i++) {
if (arrayobject[i].id === id) {
return arrayobject[i];
                }
            }
return null; // no element found
        }
var customerObj = SearchElementById(ArrayOfCustomer, '6');
if (customerObj)
        {
            document.write("<br>Result found in the array with id:" + customerObj.id +
"<br><br> customer name:" + customerObj.name +
" <br>address:" + customerObj.address +
"<br>country:" + customerObj.country);
        }
        
    </script>

Method 3: Javascript find in array of objects by property

In this example, we are using an array forEach function for Iterate over any item in the array. For each item in the array, then assign it to the filteritemobj variable.

The code defines a variable filteritemobj and initializes it to null. This variable will hold the customer object that matches the provided ID.

A function named SearchcutomerElementById() is defined, which takes one parameter id (the ID to search for).

Inside the SearchcutomerElementById() function, the forEach() method is used to iterate over each item in the ArrayOfCustomer array. For each item, it checks if the 'id' property matches the provided ID. If a match is found, the corresponding object is assigned to the filteritemobj variable.

Outside the function, the SearchcutomerElementById() function is called with the ID '4'. This searches for a customer object with the ID '4'.

If a customer object is found (i.e., filteritemobj is not null), its details are displayed using document.write(). The details include the customer's ID, name, address, and country. The information is concatenated into a string and written onto the document.

This code another approach to searching for an element in an array of objects using the forEach() method instead of a for loop. It also uses a variable (filteritemobj) outside the function to store the matched customer object.


<script type="text/javascript">
var ArrayOfCustomer =
            [
                { 'id': '1', 'name': 'Shelley Burke', 'address': 'P.O. Box 78934', 'country': 'Norway' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '3', 'name': 'Ian Devling', 'address': 'Av. das Americanas 12.890', 'country': 'Sweden' },
                { 'id': '4', 'name': 'Peter Wilson', 'address': 'Tiergartenstraße 5', 'country': 'Germany' },
                { 'id': '5', 'name': 'Sven Petersen', 'address': 'Frahmredder 112a', 'country': 'UK' },
                { 'id': '6', 'name': 'Hatlevegen 5', 'address': '3400 - 8th Avenue Suite 210', 'country': 'USA' },
                { 'id': '7', 'name': 'Marry 5', 'address': 'Brovallavägen ', 'country': 'Sweden' },
            ]
//in this example we are using array forEach function for Iterate over any item in the array.For each item in the array, then assigning it to the filteritemobj variable.
        let filteritemobj = null;
        function SearchcutomerElementById(id) {
            ArrayOfCustomer.forEach((item) => {
if (item.id === id) {
                    filteritemobj = item;
                }
            });
        }
        SearchcutomerElementById('4');
if (filteritemobj)
        {
            document.write("<br>Result found in the array with id:" + filteritemobj.id +
"<br><br> customer name:" + filteritemobj.name +
" <br>address:" + filteritemobj.address +
"<br>country:" + filteritemobj.country);
        }
        
    </script>

Method 4: Javascript get value by key in array of objects

In this example, we are using a jquery each() function for search over any object in the array. for that, you need to add the reference of jquery.

jQuery's $.each() function is used to iterate over each item in the ArrayOfCustomer array. For each item, it checks if the 'id' property matches the ID '5'. If a match is found, the corresponding object is assigned to the customerObj variable, and the loop is terminated using return false;.

After the loop, the details of the customer object stored in customerObj are displayed using document.write(). The details include the customer's ID, name, address, and country. The information is concatenated into a string and written onto the document.

This code shows how to use jQuery's $.each() function to iterate over an array and find a specific element based on a condition. Once found, the loop is terminated, and the details of the matched object are displayed.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
var ArrayOfCustomer =
            [
                { 'id': '1', 'name': 'Shelley Burke', 'address': 'P.O. Box 78934', 'country': 'Norway' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '3', 'name': 'Ian Devling', 'address': 'Av. das Americanas 12.890', 'country': 'Sweden' },
                { 'id': '4', 'name': 'Peter Wilson', 'address': 'Tiergartenstraße 5', 'country': 'Germany' },
                { 'id': '5', 'name': 'Sven Petersen', 'address': 'Frahmredder 112a', 'country': 'UK' },
                { 'id': '6', 'name': 'Hatlevegen 5', 'address': '3400 - 8th Avenue Suite 210', 'country': 'USA' },
                { 'id': '7', 'name': 'Marry 5', 'address': 'Brovallavägen ', 'country': 'Sweden' },
            ]
var customerObj = {};
        $.each(ArrayOfCustomer, function (index, item) {

if (item.id === '5') {

                customerObj = item;
return false;
            }
        });
        document.write("<br>Result found in the array with id:" + customerObj.id +
"<br><br> customer name:" + customerObj.name +
" <br>address:" + customerObj.address +
"<br>country:" + customerObj.country);
    </script>

 

Filter array of objects javascript

If you need to retrieve all matching records from the array object, you can use the filter() function. The filter() function returns all elements in the array that match the specified condition.

An array called customerarraywithduplicateobject is defined, containing several customer objects. Some of these objects have the same 'id', leading to duplicates.

The filter() method is used on customerarraywithduplicateobject to create a new array called filtercustomerarray. This new array contains only the elements whose 'id' property matches the value '2'.

There's a conditional statement if (filtercustomerarray && filtercustomerarray.length > 0) to check if the filtercustomerarray is not undefined and contains at least one element. This check ensures that if no matching customer objects are found in the array, the subsequent code block is not executed.

If filtercustomerarray is not undefined and contains elements, the forEach() method is used to iterate over each item in the filtercustomerarray array.

Inside the forEach() loop, each customer object's details are displayed using document.write(). The details include the customer's ID, name, address, and country. The information is concatenated into a string and written onto the document.

This code shows you how to filter an array of objects based on a specific condition (id === '2') and then iterate over the filtered results to display their details. It also accounts for the possibility of no matching records found in the array.


<script type="text/javascript">
var customerarraywithduplicateobject =
            [
                { 'id': '1', 'name': 'Shelley Burke', 'address': 'P.O. Box 78934', 'country': 'Norway' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },
                { 'id': '3', 'name': 'Ian Devling', 'address': 'Av. das Americanas 12.890', 'country': 'Sweden' },
                { 'id': '4', 'name': 'Peter Wilson', 'address': 'Tiergartenstraße 5', 'country': 'Germany' },
                { 'id': '5', 'name': 'Sven Petersen', 'address': 'Frahmredder 112a', 'country': 'UK' },
                { 'id': '6', 'name': 'Hatlevegen 5', 'address': '3400 - 8th Avenue Suite 210', 'country': 'USA' },
                { 'id': '7', 'name': 'Marry 5', 'address': 'Brovallavägen ', 'country': 'Sweden' },
                { 'id': '2', 'name': 'Regina Murphy', 'address': 'Calle del Rosal 4', 'country': 'Australia' },

            ]
const filtercustomerarray = customerarraywithduplicateobject.filter(x => x.id === '2');
if (filtercustomerarray && filtercustomerarray.length > 0)//check if filtercustomerarray is not undefined in case if record not find the array object
        {
            filtercustomerarray.forEach(function (item, index) {
                debugger;
                document.write("<br>Result found in the array with id:" + item.id +
"<br><br> customer name:" + item.name +
" <br>address:" + item.address +
"<br>country:" + item.country);
            })
        }
    </script>

as you can see from the above customer array in this array, we have a duplicate entry. for example, we have 3 objects with id=2. Now if we use filter() then it will return all three objects from the array.I have also attach the debugger screen-shot.

filterfunction

Filter function output

 

*Thank you so much if you have a question please comment

Array Basic Concept

Array is a special variable in JavaScript. In Javascript Arrays you can add one or more values ​​at the same time.

Array in JavaScript is used to represent a unit or group of elements in a continuous memory location. Each element that you enter in the array is stored in the array with a unique number starting from zero.

Arrays are used in JavaScript to store more than one value in a single variable. Array stores elements of the same type as a sequence in a fixed size.

For example, if you want to track the location of a user at some point in time, then you can include X and y values ​​in an array. Array is more than the examples of x and y, through Indexed you can access Data or Elements. Can be stored in Array or else you can get Elements from Array.

Array is a special variable in JavaScript. In Javascript Arrays you can add one or more values ​​at the same time.
Arrays are a collection of values ​​of the same type. By one type of value, it means that either only strings or only integers or floating point numbers etc. To avoid the problem of creating multiple variables. It is used like if you want to store the name of 200 employees.

So for that you do not need to create 200 variables, you can create an array in which you can store 200 names, doing this also saves programmers time.Every element of the arrays can be uniquely identified, stores the values ​​by indexing the array, but always remember that the index of the array starts from zero.

So in the example you mentioned, the first name will be from 0 to index and the last name will be at index 199, you can access any value of the array by the name of the array and its index number.

You should also always remember that arrays are objects in JavaScript, so you create them through new keywords, although JavaScript also provides you with the option to put values ​​directly, but even then you keep arrays as objects in JavaScript. Is

creating javascript arrays
In javascript you can create 2 types of arrays, both these methods are used according to different situation.

directly – In this method, along with creating the array, you also enter the value, this is the combined way of creating the array.
with new keyword- In this method you create array like object, in this method you first array is created and values ​​can be added later, if you want, you can put values ​​together for this. array object’s constructor is used

Array in JavaScript is used to represent a unit or group of elements in a continuous memory location. Each element that you enter in the array is stored in the array with a unique number starting from zero.

Arrays are used in JavaScript to store more than one value in a single variable. Array stores elements of the same type as a sequence in a fixed size.

For example, if you want to track the location of a user at some point in time, then you can include X and y values ​​in an array. Array is more than the examples of x and y, through Indexed you can access Data or Elements. Can be stored in Array or else you can get Elements from Array.