0

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?

Badacadabra
  • 8,043
  • 7
  • 28
  • 49
Sridher
  • 27
  • 1
  • 1
  • 8
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Qantas 94 Heavy Feb 19 '15 at 04:46
  • 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. http://jsfiddle.net/wxbvbwtp/1/ – cssyphus Mar 12 '15 at 15:15

5 Answers5

2

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

Manish Gupta
  • 1,405
  • 14
  • 32
1

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.

Ankush Jain
  • 5,654
  • 4
  • 32
  • 57
0

You can get the number of elements in an array using yourArray.length.

Samuel Goodell
  • 600
  • 2
  • 9
0

You can use .length property in order to get no of elements in an array.

Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
0
var x = '[{"name":"aaa"},{"name":"bbb"},{"name":"ccc"}]';
var y = $.parseJSON(x);

alert( y.length );

jsFiddle Demo


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

http://www.w3fools.com/


Notes:

  1. 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.

  2. Var y has been parsed into a javascript array. y.length will return the number of items in the array.

  3. You specifically asked about the length of a json array, so first you must parse the json into a javascript array.

jsFiddle comparison

cssyphus
  • 37,875
  • 18
  • 96
  • 111