Search code examples
javascriptjqueryarraysjsonencode

How to get the number of elements in a JSON array?


I'm getting json_encode data from controller. The resulting array is like:

[
  { "name": "aaa" },
  { "name": "bbb" },
  { "name": "ccc" }
]

How to get the number of elements in this array using JavaScript?


Solution

  • You can always get array length by length property of an array.

    Here is the reference from w3school:
    http://www.w3schools.com/jsref/jsref_length_array.asp

    Code:

    function myFunction() {
      var fruits = ["Banana", "Orange", "Apple", "Mango"];
      document.getElementById("demo").innerHTML = fruits.length;
    }
    <p>Click the button to create an array, then display its length.</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>

    Try the working code in fiddle:
    http://jsfiddle.net/5arrc15d/