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
- Knockoutjs binding not changing
- Is it possible to convert a string into HTTP POST variables
- Javascript for input file button in order to notify that file upload is complete
- Get the ID of MVC textbox to send to Ajax
- How to show the dropdown blank when one of the option from the otehr dropdown is selected?
- Grails jQuery-UI In Assets
- Load AJAX content for specific element (Pass DOM Element to AJAX callback function)
- Why do I get empty objects when pushing to array?
- Close HTML list, insert an element, reopen list using jQuery
- Multiple jquery Scripts on one page
- using jquery highlight effect
- Change color of an element only when another one is on hover
- Jquery - After .append, .hover on other element not working
- Jquery – Append selected items in spans
- How to show date without year of jQuery UI datepicker
- Get a users instagram images without access tokens api
- Clicking / opening Kendo UI Toolbar menu from JQuery or Protractor
- style parent element based on child elements
- JSON not being parsed by jQuery (error given)
- How many ways to ajax load page content in JQuery
- getJSON always returns the same data
- how to show sliding div alternately
- Convert jQuery to Mootools
- How do I count how many span of the same id on my page?
- Hot to map html input properties to object with jQuery?
- Uncaught TypeError: Cannot read property 'split' of undefined
- Change html title with Jquery
- drag and drop multiple file in HTML5?
- Multiple IDs in Jquery for image carousel not working
- Disallow one animation to begin until the other one ends
- Passing a function in Jquery / Javascript
- Uncaught SyntaxError Multiple Appends
- Wordpress - reference JS-file without '?ver=4.6'
- Kendo UI: Can I use a DataSource to sync data with standard HTML elements
- Jquery selector (this) not in function
- How does function invocation work in JavaScript as an value to part of an object?
- My result in my jQuery gives NaN
- Form data on load of Blueimp jQuery File Upload
- jquery show a confirm alert before submitting
- Why does firebug say my function call is "undefined"
- Jquery Plugin - Events not firing correctly
- In Laravel 5, how can I display the response after a AJAX post?
- When is a javascript code executed?
- DataTables: issue with adding rows after Ajax request
- Uncaught TypeError: Cannot read property 'offsetTop' of null (navbar)
- stop submit button from post back on ipad asp.net
- CSS issue in JQuery date picker
- Attach a return false to jquery bind
- Is it possible to check if a class is removed in jQuery
- Slide page after page fully loads
- Data method in JQuery
- Jquery how to run a function only if condition is true
- Why aren't coldfusion variables/parameters valid for content I dynamically add to the DOM?
- cannot load ajax content on superslides jquery plugin
- How to capture form submit from a page that has multiple forms
- Anchor Tags not working in IE or FF
- Jquery in JSF 2.0
- Jquery data Attribute conditional Selector
- How do you automatically change HTML Title according to its file name?
- jQuery validation remote
- JQuery selectors -- why does adding a filter return MORE elements?
- Using Javascript clone(); to make a standalone header follow the page
- -webkit-transform performance issues in chrome
- JQuery Validation plugin on a <input> with a relaxed "step" attribute
- Crop image down when scaling browser-window to given browser-window width. Then let remaining portion of image be responsive
- I want to be able to get the contents of all `<b></b>
- Auto-fill input form with PHP, MySQL and jQuery
- How do I click a list item and show it's parents?
- jquery val() doesn't change value
- Jquery data selector not returning expected object
- jQuery activate function when TD gets focus
- Ajax request with PHP on MySQL DB
- JQuery not able to read value from radio button
- Remove last two slides
- Better way than using document ready in JQuery
- How do you identify a specific selector in a multiple selector function?
- JS/CSS - Show semi-transparent layer over webpage for JS disabled users
- Alert Box to show when error occur
- jQuery Class Change
- How do I restrict image uploads to a certain height and width?
- can you stretch background height when slideDown()/slideUp() happens
- Slideshow by changing background-image CSS attribute using JQuery in Drupal 7
- Load php file to get my session using javascript
- jQuery generate multiple arrays and generate HTML
- Google maps: render map based on street address
- jQuery imgelens plugin - Uncaught TypeError: Object [object Object] has no method 'imageLens'
- JQuery Plugin won't work inside modal
- Only half of jQuery animation working. I can seem to get all of it to work
- how can I set HTML body's first table's first'row first's td's height using Jquery?
- How to get actual values from input field by javascript?
- IE8 browser freeze when running AJAX query with jQuery, jqGrid
- Get text of parent's parent?
- jQuery getScript function with frames
- How do I get the class of each ul>li item as a serial string?
- Html.DropDownList passing as null using .val() in JSON
- referenceNode.parentNode throwing undefined
- Uncaught TypeError
- Search the webpage source for urls?
- Is there a way to convert the output of a form into an array as PHP does automatically, but using jQuery/Javascript?
- How Do I Find the Index of An Element Within an Array
- How to return status when using Jquery's .load() function?
- Checking background color in javascript and alert
- Javascript Image Toolbox
- Tablesorter Default Sort On 2 Columns
- jQuery login issue
- Using MouseOver and MouseOut
- Getting width and height of images with JQuery not working
- Replacing selected with another text
- How to set asp.net hidden field in JavaScript and access the value in C# code behind
- Skip whitespacing from string
- jQuery empty out text area then append data does not work
- Grab multiple .attr values from multiple div elements with the same class
- jQuery change selected using two attributes (e.g. class and value)
- Two groups of multifile uploads
- jQuery disable enable button style
- ajax call using jsonp, how to improve security from just passing the credentials in the url
- e.keycode is undefined in firefox 19.0.2 ,chrome 25.0.1364.172 m,IE 8
- How to find a string from a line and delete the whole line
- jQuery recursion
- How to copy row into datatable and save to localStorage?
- what if jquery.js is include into the page twice?
- jQuery animate div when filled
- Adding one more event in JQuery date picker the current adding functionalities not working
- Second drop-down content dependent on first drop-down
- Returning objects in Javascript
- jqGrid grouping - hiding the group header and footer when only one row
- Specific lines in javascript function not working
- How can I get the text value of <li> with nested button?
- JQuery not appending div tag with attributes from a JS function object
- Waiting for $.post answer
- Store form data into hidden field using Jquery?
- datepicker onselect is not firing From gridmvc.js plugin
- How can i delete using ajax?
- On click isn't working for some reason .. where did I go wrong?
- jQuery change inline style of multiple div element
- Trigger event on closing of Window.open
- UNDEFINED when trying to get value of an attribute
- removing a class from a jquerymobile page
- Get values from HTML form
- Styling closedview dropdown
- PHP Ajax works with get but not with post
- adding the class active dynamically
- AJAX Form in a jQuery Popup - Need a way to clear content on popup close
- Uncheck checkbox in table with property "checked"
- If statement for jquery
- jquery rotate in IE7 only rotates once
- Cleanly chain jQuery ajax requests
- Javascript Is it OK to set boolean value in array?
- Pre select the Tab according to Day and show its contents
- How to remove my "x" close Button in marker InfoWindow?