Javascript Counting Array of Objects - javascript

I am been having trouble counting the number of objects in this array in server-side javascript.
Below is a JSON object which was parsed out using the array that I am trying to count.
NOTE: The object is in object form, not JSON string form.
JSON Object:
[{"dataSymbol":"21135103","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49652777778,"strikePrice":"33.00","last":"1.30","change":"0.20","changePct":"18.1818","lastRaw":1.3,"ask":"1.40","bid":"1.30","lastTime":40073.49652777778,"tick":0,"openInterest":"13.6K","volume":"80311","expDate":40194,"coName":"AJR Jan0 33.0 C"},
{"dataSymbol":"21339645","isHoliday":false,"isIPO":false,"lastTradeTime":40073.50479166866,"strikePrice":"6.00","last":"2.11","change":"0.01","changePct":"0.4762","lastRaw":2.11,"ask":"2.15","bid":"2.10","lastTime":40073.50479166866,"tick":0,"openInterest":"105.00","volume":"62313","expDate":40285,"coName":"EK Apr0 6.0 C"},
{"dataSymbol":"13511861","isHoliday":false,"isIPO":false,"lastTradeTime":40073.489583333336,"strikePrice":"113.00","last":"1.41","change":"-6.34","changePct":"-81.8065","lastRaw":1.41,"ask":"7.60","bid":"7.45","lastTime":40073.489583333336,"tick":0,"openInterest":"805.00","volume":"62975","expDate":40138,"coName":"SPY Nov8 113.0 P"},
{"dataSymbol":"20718334","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49375,"strikePrice":"40.00","last":"1.42","change":"-0.05","changePct":"-3.4014","lastRaw":1.42,"ask":"1.46","bid":"1.44","lastTime":40073.49375,"tick":0,"openInterest":"116.1K","volume":"60470","expDate":40194,"coName":"QQQQ Jan0 40.0 P"},
{"dataSymbol":"20348966","isHoliday":false,"isIPO":false,"lastTradeTime":40073.47708333333,"strikePrice":"41.00","last":"2.39","change":"-0.06","changePct":"-2.449","lastRaw":2.39,"ask":"2.45","bid":"2.42","lastTime":40073.47708333333,"tick":-1,"openInterest":"4.6K","volume":"60320","expDate":40257,"coName":"QQQQ Mar0 41.0 P"}]
I usually use myObject.length to count this type of array, but that is not working.
Response.Write(optionsQuotes.length);
The above code is returning a result of 21339646 as the count, when the actual count of the array is 5.
I would rather not have to loop through the array to count it, because I am looping through it later in order to draw a table, and I need to know the last iteration before the table draw begins.
Any ideas?
EDIT:
//here is where I am gettnig the array of objects...
var myObj = common.getMyObj("param1", "param2");
I serialized the object for the purpose of showing the contents of the array.
myObj.constructor is an Array.
This is on the server side also BTW.

ECMAScript doesn't handle the length of "assocative" arrays like PHP does - either use a real list that has a .length property, set the .length property manually in the JSON as you populate properties in the object, or do a for..in loop and make sure to use .hasOwnProperty and increment some counter.

Mhh... maybe is not a JSON object but an string and the length that is returning is the length of the string and not of the json array
With prototype you need to do something like
var data = '{ "name": "Violet", "occupation": "character" }'.evalJSON();
data.length
but this obviously is depending of the framework that you are using.

The bug must be somewhere else as the following
<script>
var foo = eval('[{"dataSymbol":"21135103","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49652777778,"strikePrice":"33.00","last":"1.30","change":"0.20","changePct":"18.1818","lastRaw":1.3,"ask":"1.40","bid":"1.30","lastTime":40073.49652777778,"tick":0,"openInterest":"13.6K","volume":"80311","expDate":40194,"coName":"AJR Jan0 33.0 C"},{"dataSymbol":"21339645","isHoliday":false,"isIPO":false,"lastTradeTime":40073.50479166866,"strikePrice":"6.00","last":"2.11","change":"0.01","changePct":"0.4762","lastRaw":2.11,"ask":"2.15","bid":"2.10","lastTime":40073.50479166866,"tick":0,"openInterest":"105.00","volume":"62313","expDate":40285,"coName":"EK Apr0 6.0 C"},{"dataSymbol":"13511861","isHoliday":false,"isIPO":false,"lastTradeTime":40073.489583333336,"strikePrice":"113.00","last":"1.41","change":"-6.34","changePct":"-81.8065","lastRaw":1.41,"ask":"7.60","bid":"7.45","lastTime":40073.489583333336,"tick":0,"openInterest":"805.00","volume":"62975","expDate":40138,"coName":"SPY Nov8 113.0 P"},{"dataSymbol":"20718334","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49375,"strikePrice":"40.00","last":"1.42","change":"-0.05","changePct":"-3.4014","lastRaw":1.42,"ask":"1.46","bid":"1.44","lastTime":40073.49375,"tick":0,"openInterest":"116.1K","volume":"60470","expDate":40194,"coName":"QQQQ Jan0 40.0 P"},{"dataSymbol":"20348966","isHoliday":false,"isIPO":false,"lastTradeTime":40073.47708333333,"strikePrice":"41.00","last":"2.39","change":"-0.06","changePct":"-2.449","lastRaw":2.39,"ask":"2.45","bid":"2.42","lastTime":40073.47708333333,"tick":-1,"openInterest":"4.6K","volume":"60320","expDate":40257,"coName":"QQQQ Mar0 41.0 P"}]');
document.writeln(foo.length);
</script>
yields the correct value.

I think you need to eval the string. Could 21339645 be the number of characters?

Related

Prevent JSON.parse from rearanging an object

In my web application I receive a JSON string from the server which I keep in the greetings variable:
var greetings = '{"2":"hoi","3":"hi","1":"salam"}'
Please notice how the greetings start with the index 2 and the value hoi.
Now I want to parse the JSON and the result is the following:
JSON.parse(greetings) // {1: "salam", 2: "hoi", 3: "hi"}
The order has changed, it seems like JSON.parse orders the result by key.
Is there a way to keep the order of the original string intact?
{
"2":"hoi",
"3":"hi",
"1":"salam"
}
is not an array, its an object. Objects don't have any order.
If the order is important, you need to switch to an actual array.
You generally cannot rely on the order of indices in an object. Use an array of key/value pairs instead.
As you can see the keys are parsed to (numeric) indices, which is why they are ordered that way. You could hack around this by prefixing your keys and then stripping those later:
console.log(JSON.parse('{"i2":"hoi","i3":"hi","i1":"salam"}'))

Show Json Object In TextBox

I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference

Converting an array to a string in Javascript

I have a multi-dimensional array like this:
1 2 3
4 5 6
Now I need to convert this array into a string like 1,2,3;4,5,6.
Can any one suggest how to do this, please?
simply use the join method on the array.
> [[1,2,3],[4,5,6]].join(';')
'1,2,3;4,5,6'
It's lucky that you simply don't have to consider how the apply the join method on the inner lists, because a list is joined by comma by default. when a list is coerced into a string, it by default uses commas to separate the items.
As it was already mentioned by qiao, join() is not recursive.
But if you handle the recursion yourself you should acquire the desired result, although in a rather inelegant way.
var array = [[1,2,3],[5,6,7]];
var result = [];
array.forEach(
function(el){
result.push(
el.join(",")
);
});
result.join(";");
If you need to serialize an array into a string and then deserialize it later to get an array from the string you might want to take a look at JSON:
http://www.openjs.com/scripts/data/json_encode.php
Try this:
array.toString();
See here for reference: http://www.w3schools.com/jsref/jsref_tostring_array.asp
See answer by qiao for a much nicer approach to multidimensional arrays like this.

Does JavaScript populate empty array items?

I am coding a lot of annual data in JavaScript, and I was considering adding it to arrays, using the year as the array index and putting the data into the array. However, Firebug seems to be indicating that JavaScript handles this by populating two thousand odd entries in the array with "undefined." With hundreds of such arrays kicking around in active memory, I'm worried the overhead of hundreds of thousands of useless array items could start to slow the program down. Will it?
When you set the value of a numeric index higher than the current length of your array, the length property is affected.
In brief, you should use an Object:
var data = {};
data[year] = "some data";
// or
var data = {
2009: "2009 data",
2010: "2010 data"
};
Now I answer the question title: "Does JavaScript populate empty array items?"
No, as I said before, only the length property is changed, (if necessary, only if the index added is larger than the current length), length is incremented to be one more than the numeric value of that index.
The Array.prototype methods work assuming that the array object will have its indexes starting from zero.
The previous indexes don't really exist in the Array object, you can test it:
var array = [];
array[10] = undefined;
array.hasOwnProperty(10); // true
array.hasOwnProperty(9); // false
In conclusion, arrays are meant to contain sequential indexes, starting from zero, if your properties don't meet those requirements, you should simply use an object.
Yes, most likely. You should consider using a JavaScript object instead:
var years = {2009: 'Good', 2010: 'Better'};
Well, if you iterate over many thousands of undefined, it will affect overall program speed, not sure if you'll notice it though.
On the other hand, sometimes a sparse array is simpler to use than a custom object,
and arrays have such handy methods available.
In a calendar application I begin with objects for each year in use, but each year consists of a twelve member (months array) and each 'month' is a sparse array of significant dates, whose lengths depend on the highest date of that month that has any data.

JSON conversion in javascript

I'm trying to stringify a multi-array variable into a JSON string in Javascript. The
//i'm using functions from http://www.json.org/json2.js
var info = new Array(max);
for (var i=0; i<max; i++) {
var coordinate = [25 , 32];
info[i] = coordinate;
}
var result = JSON.stringify(info);
But result doesn't look like a JSON string at all. What am I doing wrong here?
You, and many in this question, are confused about the JSON specification. The string you have is a valid JSON array.
From json.org
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record,
struct, dictionary, hash table,
keyed list, or associative array.
An ordered list of values. In most languages, this is realized as
an array, vector, list, or
sequence.
Your example matches the second structure - the ordered list of values.
Also from json.org:
An array is an ordered collection of
values. An array begins with [ (left
bracket) and ends with ] (right
bracket). Values are separated by ,
(comma).
A value can be a string in double
quotes, or a number, or true or false
or null, or an object or an array.
These structures can be nested.
Doesn't leave much to the imagination. You've got a valid JSON array there. Have fun with it. But just to be annoyingly thorough:
From the RFC
RFC 4627, Section 2
2) JSON Grammar
A JSON text is a sequence of
tokens. The set of tokens includes
six structural characters, strings,
numbers, and three literal names.
A JSON text is a serialized object
or array.
JSON-text = object / array
The result looks like this for me:
[[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32]]
Which is fine as far as I can see. It might look a bit weird, but that is mostly because JSON is used a lot for objects, which have a slightly different notation. You can eval the string and get the array structure back though, so it looks fine to me.

Categories