Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of JSON array in AngularJS

I am using AngularJS to render html page doing ajax call, which returns json file.

How to get count of id's in below JSON using angularjs?

[{"id":1,"Name":"Apple"},
 {"id":2,"Name":"Mango"},
 {"id":3,"Name":"Banana"}
 {"id":4,"Name":"Coconut"}
 {"id":5,"Name":"pineaple"}
 {"id":6,"Name":"Orange"}
 {"id":7,"Name":"Guava"}]
like image 344
Ravi Ranjan Avatar asked Jul 04 '14 13:07

Ravi Ranjan


People also ask

How do I find the length of a JSON array?

To obtain the size of a JSON-encoded array or object, use the json_size function, and specify the column containing the JSON string and the JSONPath expression to the array or object.

How is JSON size calculated?

Use measureLength() to compute the number of characters that will be printed by printTo() . Use measurePrettyLength() to compute the number of characters that will be printed by prettyPrintTo() .

How do you find the number of elements in a JSON array?

JsonArray::size() gets the number of elements in the array pointed by the JsonArray . If the JsonArray is null, this function returns 0 . Internally, this function walks a linked-list to count the elements, so its time complexity is O(n). Don't use this function to create a for loop; instead, use iterators.

How do I count the number of records in a JSON file?

Use len() to count the items in a JSON object Call len(obj) to return the number of items in a JSON object obj .


3 Answers

You don't need Angular to get the length of that.

In this case, your parsed JSON is a simple array, you can get the length with:

obj.length

assuming that obj contains your parsed JSON as such:

var obj = [{"id":1,"Name":"Apple"},
{"id":2,"Name":"Mango"},
{"id":3,"Name":"Banana"}
{"id":4,"Name":"Coconut"}
{"id":5,"Name":"pineaple"}
{"id":6,"Name":"Orange"}
{"id":7,"Name":"Guava"}]
like image 111
Lorenzo Marcon Avatar answered Oct 06 '22 23:10

Lorenzo Marcon


var json=
[{"id":1,"Name":"Apple"},
{"id":2,"Name":"Samsung"},
{"id":3,"Name":"Nokia"}
{"id":4,"Name":"Motorola"}]

  var count = Object.keys(json).length;
  console.log(count);
like image 39
Akash Chatterjee Avatar answered Oct 07 '22 00:10

Akash Chatterjee


In your HTML, lets say your array is "comments" (a common use-case):

{{ comments.length }}

You can also do a ng-hide="{{ comments.length}}" on an element that says something to the effect of "no comments".

like image 3
Domenic Merenda Avatar answered Oct 07 '22 00:10

Domenic Merenda