In this post, We will discusshow we can Find object by id in an array of JavaScript objects. I have an array of objects, which contain a list of named objects, and I need to get the object where “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.

get array by value

Find a value in an array of objects in Javascript

Let’s take a real-time example for finding a value in an array of objects in Javascript. I have created an HTML page in which I have a text input in which the user can input the id. and based on that id, I’m going to search for the object by its id, and then I will show that object in the div.

 

<!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.

<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.

<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.

<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 require to get all of the matching records from the array object, then we can use the filter() function, The filter() function returns all elements in the array if an element in the array object matches.

<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.

The post Find object by id in an array of JavaScript objects appeared first on Software Development | Programming Tutorials.



Read More Articles