{"id":663,"date":"2020-08-27T11:39:37","date_gmt":"2020-08-27T11:39:37","guid":{"rendered":"https:\/\/datatype.co.in\/blog\/?p=663"},"modified":"2020-08-27T11:47:28","modified_gmt":"2020-08-27T11:47:28","slug":"handling-array-of-objects-in-javascript","status":"publish","type":"post","link":"https:\/\/datatype.co.in\/blog\/handling-array-of-objects-in-javascript\/","title":{"rendered":"Handling Array of Objects in JavaScript"},"content":{"rendered":"\n<p>If you are working with APIs, most of the time you will encounter arrays of objects. In this article you will learn how array of objects should be handled for further processing of received data or for presenting the data in UI in various forms like table, list and so on. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var arr = [ \n    { name: 'Ravi', age: 20 },\n    { name: 'Ajay', age: 55 },\n    { name: 'Henry', age: 15 }\n];<\/code><\/pre>\n\n\n\n<p>Let&#8217;s say an API is returning an array of objects as shown in the example above. How would you loop and present the data in UI?<\/p>\n\n\n\n<p><strong>Looping Array of Object:<\/strong><\/p>\n\n\n\n<p>In order to display data in UI, you have to loop through each object (element) and display the property value. Since it is an array, you can use <strong><code>forEach()<\/code><\/strong> array method to loop through. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>arr.forEach(function(element){\n    \/\/ element is object here. \n    console.log(element.name, element.age);\n})\n\/\/ Output:\nRavi 20\nAjay 55\nHenry 15<\/code><\/pre>\n\n\n\n<p>In the above example, we are passing a function in as an argument in the <strong><code>forEach()<\/code><\/strong> function. Such functions are know as <strong>callbacks <\/strong>in JavaScript. <\/p>\n\n\n\n<p>You can learn more about callbacks in this article: <a rel=\"noreferrer noopener\" aria-label=\"What is Callback in JavaScript  (opens in a new tab)\" href=\"https:\/\/datatype.co.in\/blog\/what-is-callback-in-javascript\/\" target=\"_blank\">What is Callback in JavaScript <\/a><\/p>\n\n\n\n<p> The dot <strong><code>(.)<\/code><\/strong> operator is used to access object property values. Apart from <strong>element <\/strong>argument, the callback accepts second optional argument which provides the <strong>index <\/strong>of each element in the array.  <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>arr.forEach(function(element, index){\n    \/\/ element is object here. \n    console.log(index, element.name, element.age);\n})\n\/\/ Output:\n0 Ravi 20\n1 Ajay 55\n2 Henry 15<\/code><\/pre>\n\n\n\n<p>Now, let&#8217;s try to display the data in a tabular form in UI using jQuery.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n&lt;script>\n$(document).ready(function(){\n   arr.forEach(function(element, index){\n     index = index + 1;\n     \/\/ Create row\n     var row = \"&lt;tr>&lt;td>\" \n             + index + \"&lt;\/td>&lt;td>\"\n             + element.name + \"&lt;\/td>&lt;td>\" \n             + element.age + \"&lt;\/td>&lt;\/tr>\";\n\n     \/\/ Append row in table body\n     $(\"#listUser tbody\").append(row);\n   })      \n})\n&lt;\/script>\n\n\/\/ Static HTML markup for table\n&lt;table id=\"listUser\">\n        &lt;thead>\n            &lt;tr>\n                &lt;th>Sl&lt;\/th>\n                &lt;th>Name&lt;\/th>\n                &lt;th>Age&lt;\/th>\n            &lt;\/tr>\n        &lt;\/thead>\n        &lt;tbody>  \n            &lt;!-- Rows will be added dynamically here -->  \n        &lt;\/tbody>\n&lt;\/table><\/code><\/pre>\n\n\n\n<p>What we are doing here is looping through the array of object and creating <strong><code>table<\/code><\/strong> rows  <strong><code>&lt;tr><\/code><\/strong> and adding value to <strong><code>&lt;td><\/code><\/strong> dynamically. Then appending each rows in the <strong><code>table body<\/code><\/strong> having <code><strong>id = \"listUser\"<\/strong><\/code>.  The loop will iterate three times as there are three elements in the array and consequently three table rows would be generated.<\/p>\n\n\n\n<p>Here is complete example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html>\n&lt;html lang=\"en\">\n&lt;head>\n&lt;meta charset=\"utf-8\">\n&lt;title>Table Demo&lt;\/title>\n&lt;style>\n    table{\n        width: 100%;\n        margin-bottom: 20px;\n\t\tborder-collapse: collapse;\n    }\n    table, th, td{\n        border: 1px solid #cdcdcd;\n    }\n    table th, table td{\n        padding: 10px;\n        text-align: left;\n    }\n&lt;\/style>\n&lt;script src=\"https:\/\/code.jquery.com\/jquery-1.12.4.min.js\">&lt;\/script>\n&lt;script>\n    $(document).ready(function(){\n     var arr = [ \n        { name: 'Ravi', age: 20 },\n        { name: 'Ajay', age: 55 },\n        { name: 'Henry', age: 15 }\n\t ];\n     arr.forEach(function(element, index){\n       index = index + 1;\n       \/\/ Create row\n       var row = \"&lt;tr>&lt;td>\" \n             + index + \"&lt;\/td>&lt;td>\"\n             + element.name + \"&lt;\/td>&lt;td>\" \n             + element.age + \"&lt;\/td>&lt;\/tr>\";\n\n       \/\/ Append row in table\n       $(\"#listUser tbody\").append(row);\n     })    \n  });    \n&lt;\/script>\n&lt;\/head>\n&lt;body>\n    &lt;table id=\"listUser\">\n        &lt;thead>\n            &lt;tr>\n                &lt;th>Sl&lt;\/th>\n                &lt;th>Name&lt;\/th>\n                &lt;th>Age&lt;\/th>\n            &lt;\/tr>\n        &lt;\/thead>\n        &lt;tbody>\n            &lt;!-- Rows will be added dynamically here -->  \n        &lt;\/tbody>\n    &lt;\/table>\n&lt;\/body> \n&lt;\/html><\/code><\/pre>\n\n\n\n<p> Add the above code in a HTML file and open it in a browser. You would see a dynamically generated table as shown below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"662\" height=\"165\" src=\"https:\/\/datatype.co.in\/blog\/wp-content\/uploads\/2020\/08\/image-1.png\" alt=\"Handling Array of Objects in JavaScript\" class=\"wp-image-673\" srcset=\"https:\/\/datatype.co.in\/blog\/wp-content\/uploads\/2020\/08\/image-1.png 662w, https:\/\/datatype.co.in\/blog\/wp-content\/uploads\/2020\/08\/image-1-300x75.png 300w\" sizes=\"auto, (max-width: 662px) 100vw, 662px\" \/><\/figure>\n\n\n\n<p>If you found this article useful, please leave your thoughts in the comment box below.<\/p>\n\n\n\n<p>You may also like:<br><a rel=\"noreferrer noopener\" aria-label=\" Important JavaScript Array Methods (opens in a new tab)\" href=\"https:\/\/datatype.co.in\/blog\/important-javascript-array-methods\/\" target=\"_blank\">Important JavaScript Array Methods<\/a><br><a href=\"https:\/\/datatype.co.in\/blog\/sort-array-of-objects-by-property-value-in-javascript\/\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\"Sort Array of Objects by Property Value in JavaScript (opens in a new tab)\">Sort Array of Objects by Property Value in JavaScript<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you are working with APIs, most of the time you will encounter arrays of objects. In this article you will learn how array of objects should be handled for&nbsp;[ &hellip; ]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[177,176,157,216,100,215],"class_list":["post-663","post","type-post","status-publish","format-standard","hentry","category-javascript","tag-array-of-objects","tag-javascript","tag-javascript-foreach-loop","tag-jquery-loop-array-of-objects","tag-js-interview-question","tag-loop-array-of-objects","list-style-post"],"_links":{"self":[{"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/posts\/663","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/comments?post=663"}],"version-history":[{"count":20,"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/posts\/663\/revisions"}],"predecessor-version":[{"id":684,"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/posts\/663\/revisions\/684"}],"wp:attachment":[{"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/media?parent=663"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/categories?post=663"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/datatype.co.in\/blog\/wp-json\/wp\/v2\/tags?post=663"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}