How to find length of JSON using JSON.parse? - javascript

I have a Json like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"}}.
So ideally i should get length as 1 considering i have only 1 value on 0th location.
what if i have a JSON like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},"1":{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}}
I am getting the value as undefined if i do alert(response.length); where response is my JSON as mentioned above
Any suggestions?

Objects don't have a .length property...not in the way you're thinking (it's undefined), it's Arrays that have that, to get a length, you need to count the keys, for example:
var length = 0;
for(var k in obj) if(obj.hasOwnProperty(k)) length++;
Or, alternatively, use the keys collection available on most browsers:
var length = obj.keys.length;
MDN provides an implementation for browsers that don't already have .keys:
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};
Or, option #3, actually make your JSON an array, since those keys don't seem to mean much, like this:
[{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}]
Then you can use .length like you want, and still access the members by index.

let _json = '{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},"1":{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}}';
let your_json = $.parseJSON(_json);
const size = Object.keys(your_json).length;

Related

Checking for the last element in a JQuery each function

I have an object that I am iterating through using JQuery's each function. However, the solution posted in this stack overflow post doesn't work when I tried using the length property. I got undefined in the console when I tried getting a length property value, which I believe this is because I am iterating through an object and not an array.
My code:
$.each(attributes, function(key, value) {
attrKey = key;
attrVal = value;
console.log(attributes.length); //returns undefined
//do something if it is the last element
});
Try plain Javascript instead:
for (var key in attributes) {
var value = attributes[key];
// process key,value...
}
Edit:
If you're trying to get the last key/value in an object, you can't. Javascript objects are unordered, meaning that they do not keep track of when additional key/value assignments are made. If order is important, I would recommend changing attributes be an array of objects, where each object is a single key/value, or use a 3rd party library, like this - https://github.com/trentrichardson/Ordering.
If you'd like to get the number of keys in attributes, use Object.keys:
Object.keys(attributes).length
Try
var index = 1;
$.each(attributes, function(key, value) {
if(Object.keys(attributes).length == index)
{
// Do something
}
index++;
});
per #PaulFrench's comment:
length = Object.keys(attributes).length;
if(n < length) {
//do something
}

How to remove all undefined keys from a javascript array (hopefully when creating the array?)

I have placed my frustrations into a jsfiddle to observe here: http://jsfiddle.net/8ShFr/1/
var brand_new_array = new Array();
brand_new_array[10] = "random array value";
alert('why does this array have a length of ' + brand_new_array.length + '???');
I am doing some calculations client side that require me to set javascript array keys of 1M+ in number.
Not knowing exactly what that number is demands that I iterate through the first 1M+ empty array values before getting to an array key that holds data.
I simply want to set a single large key value for a javascript array without creating a bunch of empty keys before it?
I am using jQuery.each to iterate over the array, and it keeps going through array[0], array[1], array[2], etc... when I only set array[123125] for example.
Just filter out the undefineds.
brand_new_array = brand_new_array.filter(function(n){return n !== undefined});
The reason for the length being 10 is that an array's length is set to the largest index number in the array. However, this does not mean there are 9 other values in there because in javascript an array is at its base an object.
The length is just a property in the object. Arrays in javascript are at their core objects (Array Object 1). They merely act like arrays through an api.
"Whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index" 1
1. ECMAScript Language Specification 15.4 Array Objects
You probably want to just use an object with strings for keys (the keys can be the toString() of Numbers, which will happen automatically if you try to use numbers).
var sparse_array_obj = {};
sparse_array_obj[10003210234] = 4; // Fair dice roll
sparse_array_obj[5] = 17; // Truly random number
sparse_array_obj[900] = Math.random(); // Pseudorandom number
for(var i in sparse_array_obj)
console.log(sparse_array_obj[i]);
The downside is that Javascript provides no guarantees about the iteration order through an object (since its keys are unordered by definition). There are however ways around this, such as:
// Sort the keys in numeric order
var sorted_keys = Object.keys(sparse_array_obj).sort(function(a, b){ return a - b; });
for(var i = 0; i < sorted_keys.length; i++)
console.log(sparse_array_obj[sorted_keys[i]]);
Object.keys needs to be shimmed in older browsers.
var brand_new_array = new Array();
brand_new_array[10] = "random array value";
var result = brand_new_array.filter(function(e) { return e != undefined;})[0];
alert(brand_new_array.indexOf(result));
Travis J is right. The array in your example only contains one entry, but your use of jQuery.each() is making you think there are 10 entries because it iterates from 0 up to the highest index number of the array (defines the length). This is from the jQuery.each() API documentation.
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
Going back to your example:
var brand_new_array = new Array();
brand_new_array[10] = "random array value";
This will result in only one console.log output:
for(var i in brand_new_array)
console.log(brand_new_array[i]);
This will result in 10 console.log outputs:
$(brand_new_array).each( function(i,e) { console.log(e) })
Similarly, this will result in 10 console.log outputs:
for (var i=0;i<brand_new_array.length;i++)
console.log(brand_new_array[i]);
If you really want to stick with using .each() then you can skip the undefined indices like so:
$(brand_new_array).each( function(i,e) {
if (this.hasOwnProperty(i)){ console.log(e) }
})
Filter the falsy items - including undifined:
var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];
var b=a.filter(Boolean); // [1,2,"b",{},3,5]
The length is 11 because the index starts at 0.
x[0] = undefined
x[1] = undefined
x[2] = undefined
x[3] = undefined
x[4] = undefined
x[5] = undefined
x[6] = undefined
x[7] = undefined
x[8] = undefined
x[9] = undefined
x[10] = "random array value"

Jquery fill object like array

This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).

Javascript sort multi-dimensional array - a complete example?

I'm no Javascript expert and I'm having problems trying to glue together the various nuggets I find here and elsewhere regarding multi-dimensional arrays and sorting and wondered if someone could help me with a complete example?
I have managed to get to the point that I can populate a localStorage with data read in via Ajax.
The format of the rows is ...
(msgXXX) (Key1:Value1|Key2:Value2|Key3:Value3|...etc)
where
(msgXXX) is the localStorage key; and
(Key1:Value1|Key2:Value2|Key3:Value3|...etc) is the single concatenated localStorage data string
What I want to be able to do is convert all this to a multi-dimensional array to which I can apply various sorts. For example, one of the Keys is called "Timestamp" and the value is an integer representing seconds since the Unix epoch. I would like to sort all rows based on this Timestamp value (in descending order - ie latest first). Right now the dataset is just over 600 rows.
I'm comfortable I can do the extraction and slicing and dicing to get the data out of the localStorage, but I'm not even sure what I'm aiming for with regards to populating an array and then setting up the sort.
Can someone point me in the right direction?
You can go with something like this:
function create(line) {
var tokens = line.split("|");
var obj = {};
for (var i = 0; i < tokens.length; i++) {
tokens[i] = tokens[i].split(":");
obj[tokens[i][0]] = tokens[i][1];
}
return obj;
}
var arr = [];
for (....) { // iterate over the input that each line is of key/value format
arr.push(create(line));
}
function timestampSort(a, b) {
if (a == b)
return 0;
return a.timestamp < b.timestamp ? -1 : 1;
}
// to sort by timestamp
arr.sort(timestampSort);
This code creates an object per key/value line, in the format you gave. The object will have the keys as attributes. All of those objects are being pushed into an array, which is then being sorted by passing a compare function to the native sort method of array.
You can of course make as many compare functions as you want, each comparing by a different attribute/criteria.
You can read more about the sort method here: http://www.w3schools.com/jsref/jsref_sort.asp
EDIT
The sort method both changes the array itself and returns the array, so doing something like:
console.log(arr.sort(timestampSort));
Will both change the actual array and return it, and so the console.log will print it.
If you don't want to change the original array and have a copy of it that will get sorted you can:
var arr2 = arr.slice();
arr2.sort(timestampSort);
As for the keys in the array, what I wrote was intended to work only with this part of the line: Key1:Value1|Key2:Value2|Key3:Value3|...etc
So, to add support for the entire format, here's the modification:
function create(line) {
var parts = line.match(/^\(msg(\d+)\) \((.+)\)$/);
var tokens = parts[2].split("|");
var obj = { msgID: parts[1] };
for (var i = 0; i < tokens.length; i++) {
tokens[i] = tokens[i].split(":");
obj[tokens[i][0]] = tokens[i][1];
}
return obj;
}
If you apply this to the example you gave you'll get this:
arr is: [{
msgID: XXX,
Key1: Value1,
Key2: Value2,
Key3: Value3
}]
Hope this clears things for you.

get size of JSON object

i have a JSON object that gets returned by an AJAX request and I am having some trouble with the .length because it keeps returning undefined. Just wondering if I'm using it right:
console.log(data.length);
console.log(data.phones.length);
They both return undefined even though they are valid objects.
Update:
Sample of the JSON object returned:
{"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}
You can use something like this
var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}
var count = Object.keys(myObject).length;
console.log(count);
Your problem is that your phones object doesn't have a length property (unless you define it somewhere in the JSON that you return) as objects aren't the same as arrays, even when used as associative arrays. If the phones object was an array it would have a length. You have two options (maybe more).
Change your JSON structure (assuming this is possible) so that 'phones' becomes
"phones":[{"number":"XXXXXXXXXX","type":"mobile"},{"number":"XXXXXXXXXX","type":"mobile"}]
(note there is no word-numbered identifier for each phone as they are returned in a 0-indexed array). In this response phones.length will be valid.
Iterate through the objects contained within your phones object and count them as you go, e.g.
var key, count = 0;
for(key in data.phones) {
if(data.phones.hasOwnProperty(key)) {
count++;
}
}
If you're only targeting new browsers option 2 could look like this
you dont need to change your JSON format.
replace:
console.log(data.phones.length);
with:
console.log( Object.keys( data.phones ).length ) ;
Consider using underscore.js. It will allow you to check the size i.e. like that:
var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3
var json=[{"id":"431","code":"0.85.PSFR01215","price":"2457.77","volume":"23.0","total":"565.29"},{"id":"430","code":"0.85.PSFR00608","price":"1752.45","volume":"4.0","total":"70.1"},{"id":"429","code":"0.84.SMAB00060","price":"4147.5","volume":"2.0","total":"82.95"},{"id":"428","code":"0.84.SMAB00050","price":"4077.5","volume":"3.0","total":"122.32"}]
var obj = JSON.parse(json);
var length = Object.keys(obj).length; //you get length json result 4
try this
$.parseJSON(data).length
use this one
Object.keys(jsonObject).length
$(document).ready(function () {
$('#count_my_data').click(function () {
var count = 0;
while (true) {
try {
var v1 = mydata[count].TechnologyId.toString();
count = count + 1;
}
catch (e)
{ break; }
}
alert(count);
});
});

Categories