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?
Share Improve this question edited May 30, 2017 at 14:44 Badacadabra 8,5357 gold badges31 silver badges54 bronze badges asked Feb 19, 2015 at 4:44 SridherSridher 271 gold badge1 silver badge8 bronze badges 2- possible duplicate of Access / process (nested) objects, arrays or JSON – Qantas 94 Heavy Commented Feb 19, 2015 at 4:46
-
1
The newly-selected answer has nothing whatsoever to do with
json
. Please amend your question/title to remove all references to json if you wish to remain with that answer. Thank you. jsfiddle/wxbvbwtp/1 – cssyphus Commented Mar 12, 2015 at 15:15
5 Answers
Reset to default 1You can always get array length by length property of an array.
Here is the reference from w3school:
http://www.w3schools./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/5arrc15d/
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 get the number of elements in an array using yourArray.length
.
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 );
jsFiddle Demo
Best references:
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://developer.mozilla/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
http://www.w3fools./
Notes:
Var
x
is not an array, it is a string -- a json string. Alertingx.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.
jsFiddle parison