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?
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?
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:
<p>Click the button to create an array, then display it's length.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length;
}
</script>
Try the working code in fiddle:
http://jsfiddle.net/5arrc15d/
Hope it helps.
Thanks
You will have to use .length
property of array to get number of items in array.
var arr=[{"name":"aaa"},{"name":"bbb"},{"name":"ccc"}];
alert(arr.length)
Here in alert you will get number of items in array arr.
You can use .length property in order to get no of elements in an array.
var x = '[{"name":"aaa"},{"name":"bbb"},{"name":"ccc"}]';
var y = $.parseJSON(x);
alert( y.length );
Best references:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Notes:
Var x
is not an array, it is a string -- a json string. Alerting x.length
will return the length of the string, not the length of the array.
Var y
has been parsed into a javascript array. y.length
will return the number of items in the array.
You specifically asked about the length of a json
array, so first you must parse the json into a javascript array.