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.
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>
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.
*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
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- how to make page reveal effect on scrolling with jquery
- Group & count objects in array of objects by lat & lng
- Jquery Slider UI for displaying Overlay Layer in OpenLayers based on Opacity
- jquery click a link
- Check box click not working when we put it in column which is clickable
- Background image slideshow transition issue
- Add Margin on Smooth Scroll
- dynamic fields class change per list element and Js to recognize part of the class
- How do I get jQuery to change classes according to an If/Then statement. My 'home' link will not change class when another link clicked on
- How do I Get a URI segment from the CodeIgniter view where an Ajax request is made?
- Linkify (plain url to link) based on windowSize
- White tooltip with white arrow visible on white backgound
- Multiple dynamic forms submit and run function after
- How to change a textbox text with prevAll()
- How to drag and drop divs with jQuery without using jQuery UI?
- jQuery Validate with appended form element
- How do I add "disabled" class to the div "A" if div "B" has an "active" class with jquery?
- Rails 6.0.4 remote: true does not js/ajax render _partial.html.erb in browser
- Change event not updating selects with value
- Jquery show tr based on drop down
- Insert after dynamic parent div?
- Cascading dropdown with JSON not bringing new records
- In virtual table click function is not working
- jQuery - How can I open a URL in list using Enter key
- jQuery Validation not showing correct errors when overriding errorPlacement
- Show top menu bar when mouse enters a div
- How to resize logo size for mobile version of wordpress website?
- resizing an element with jscrollpane
- Refresh and Delete Marker on Google Maps
- Canvas coordinates changed with jquery
- Javascript alert messages and program flow
- Remove Slide in Jquery bxslider
- Load more hide previous content
- how to use json array to input into localstorage?
- How can I animate an element from a static layout position to an absolute layout position?
- Execute javascript code as html
- Implementing 2 bootstrap carousels on one page?
- JQuery UI Dialog not scrolling horizontally - text adjusted to dialog size
- why angular-datatables plugin buttons doesn't work
- Track hovered elements and ignore rest in certain time frame
- JQuery siblings.data() doesn't return the correct value
- JQuery - Concatenate multiple/variable table values into a string
- Unable to emit event when a checkbox is clicked. (socket.io)
- How do I get the row (and its index) in an html table from a button click inside a cell in that row
- Hiding JQuery Accordion Content From View
- Treegrid 9.3.11 not loading in chrome 61
- jquery datepicker - wrap week number in tags
- make new image-request on click
- Styling a countdown timer in jQuery
- Jquery focus is not working with slick slider
- How to run a function after one is done (or after an item in an array loads)?
- ias is undefined while adding event
- Session getting terminated after 30+ minutes of inactivity automatically?
- Handsontable not loading with dynamically created column headers
- Check if cursor is end of input text
- .select() is not workig for td while tr append through jquery
- Can't use two .replace() for one element
- Full calendar to Excel and .pdf
- how to create a smooth animated hover background following pointer
- jQuery trigger function on change
- How to set a Headline for JQuery autocomplete
- Simple JavaScript button click event will not fire
- jqGrid Disable Date Picker Value for Inline Edit
- Binding an action to an element inside an iframe using jQuery
- moving a div according to mouse position
- Submitting input reveals second input but both fields sent to handler
- Javascript: How to use an object's attribute if I have it like text
- Print file name from type=file button
- Bootstrap - navbar scrolling
- jqplot - Canvas overlay not working in a Candle Stick Chart
- Why does Ajax form submit twice?
- jquery loops using .each to detect width and height
- How to synchronize $.each(); function with called function in it?
- How to get the value of row field (nested object) using jquery
- ul dropdown list disappears when clicking inside
- can't unbind custom handler from document.keydown event
- jQuery iosslider Page scroll
- I want to be able to remove a div element when the window is smaller than 900 px. How do I do that?
- how to post multiple values via ajax $.post method to php script?
- Create dropdown list with json data
- Multiple select menus onChange update specific select menu by name through ajax call
- regarding AJAX, symfony2 - contollerAction
- How do I get users information using javascript/jquery - session/cookies/etc
- start date end date validation -Jquery/javascript - kendoUI
- how to cycle through table to pick up element values
- Run jQuery ajax in custom intervals
- "UnExpected Token Illegal" Error Message when prepend to DOM element using Jquery
- Passing values from jquery.ajax to php
- JS scroll till element is in the middle of viewport
- uncaught typeerror object has no method "tooltip"
- Accordion to scroll to current open item
- Javascript: DOM elements updated via jquery.get() aren't responding to extant page listeners
- TypeError: $ is not a function (Magnific Popup)
- How to copy the contents of two divs to the clipboard at one time
- can't get data from mysql in highchart
- Two jQuery plugin conflicting on the same page
- Range Slider - Run function during slide not working?
- How to make Image Carousel Controls 'next' and 'previous'
- How to freeze html created by CKEditor plugin
- JQuery autocomplete from database with asp.net
- How to set as selected a new value from a select list with select2 and Twig templating?
- jQuery "Back-to-top" arrow jumps to top of page before scrolling
- jquery - Syntax error, unrecognized expression:
- What's the Best Way to Apply Numbering to a Jquery Sortable list?
- Use jquery plugin within angular
- How to validate input in a field on webpage without reloading the webpage?
- Getting Values from Multiple Dropdown Menus jQuery
- radio button click doesn't work
- "toggleClass()" not working properly
- Bootstrap on click menu Scroll up, When clicked
- How to hide lightSlder's nav bar?
- append url with # using ajax
- Ajax if JSON value is null set to blank or n/a
- How to set a different position of a div if I insert a paragraph in my textarea
- Single user action firing two events - second event doesn't trigger
- How to make Slider similar/gallery to the Amazon product Slider
- jQuery Week Calendar without overlapping events
- clearing the content of the html editor
- Handling multiple Ajax requests
- Scroll to and Make Div Flash?
- how to apply transform rotate all browse in inline css using jquery
- using one html page's dropdown list to another html page
- Firing a function on page load using jQuery/Coffeescript
- can someone explain to me !lockButton in this jquery
- How to do something like jQuery's $("#formID").submit() event using angularJS?
- Map json to model .net mvc 4.5.2
- How to remove Location Hash in url using JavaScript or JQuery
- Issue linking images to dynamically created jquery elements
- .toggle() only hiding it's target element, not toggling states on alternate clicks
- asp.net mvc3,razor,jquery mobile view Navigation problem
- Remove the style attribute from a specific tag
- get a CouchDB attachment and show it on a html page
- Different headers in Angularjs and JQuery, while POSTing to Web Api
- How can I split a string based on three delimiters?
- Jquery - Adding event to specific div that shares class name with others
- Trying to append html to 'td's with multiple tables. What selector should I use?
- Javascript- callback function for start, stop, reset buttons?
- Can't SlideToggle() class under h2
- Show "Loading/Loader/Progress Bar" after button click in ASP.NET (Web Form)
- jquery disable auto scroll dragging element in body
- How to prevent postback on asp button while displaying a popup using JQuery
- How do i get my svg's to fill in the window height like images do with this codepen animation. (Greensock js)
- How can I accesss to the elements of array objects?
- find all hash # links in a div and remove hash for the last twenty ones
- Using jquery to set a value to every input if checkbox is enabled
- Javascript override problem class xml
- How to fade in and out between elements?
- how to turn jquery object into usable html?
- Jquery get input value from another text input value and set into hidden input value
- jQuery Ajax load many of the same things