Can this be done quickly in jQuery before I start looping through them? Or would I need to also setup a separate group in the response of data with the total count as lets say.. the first variable?
The common response looks something like this:
[
{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
,{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
]
But would I use jQuery to return 2 as the total count (before I loop through them all?) Or would I need to do something like this?
[
{"total":"2"}
,{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
,{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
]
Whats the most efficient/common (optimization-wise) way of doing this?
As after json decoding you are getting an array of objects(from what you have posted). You can always access the
lengthproperty of that to get total count.As you have got this array, I assume you have been able to parse the json response into a JS object. You can use
dataType: 'json'to tell jQuery to do that automatically for you or you can parse that yourself usingjQuery.parseJSON()but that is necessary if you setdataType:'json'or setcontent-Typeheader toapplication/jsonfrom server.So you can do something like this
So you dont need to send the
total countback from server. You can get that with JS after getting the response and that will make it easier for you traverse that response using$.eachas the whole array contains same type of objects (doesn’t have any special{"total":"2"}member).Note: The
lengthproperty is Pure vanilla JS, it has nothing to do withjQuery.