The jList property of the object is just a string, so you need to convert it to a Javascript object using JSON.parse().
// Dummy of your "data" variable
var data = {"jList":"[{\"added_by\":\"Ani\",\"description\":\"example description.\",\"start_date \":\"2014-10-10\",\"mark\":255,\"id\":975},{\"added_by\":\"Ani\",\"description \":\"example description..\",\"start_date\":\"2014-10-10\",\"mark\":255,\"id\":980 }]"};
var myList = JSON.parse(data.jList);
alert(myList.length); // Alerts "2"
Answer from Jan on Stack OverflowThe jList property of the object is just a string, so you need to convert it to a Javascript object using JSON.parse().
// Dummy of your "data" variable
var data = {"jList":"[{\"added_by\":\"Ani\",\"description\":\"example description.\",\"start_date \":\"2014-10-10\",\"mark\":255,\"id\":975},{\"added_by\":\"Ani\",\"description \":\"example description..\",\"start_date\":\"2014-10-10\",\"mark\":255,\"id\":980 }]"};
var myList = JSON.parse(data.jList);
alert(myList.length); // Alerts "2"
"jList":"[{\"added_by\":\"... is not an array, it's a string (and that's why it's length is 456 or 200 if you change the question).
Remove the surrounding double-quotation marks for it to be an array. Then you'll have Array.prototype.length.
See this fiddle: https://jsfiddle.net/x983vvr6/2/
Essentially, assuming you have correctly set up the object you simply need to call
OrderStatusArray.length
And it will display the length of the array.
What length are you expecting? 3 is the correct answer and the answer which this fiddle shows.
Full code:
var OrderStatusArray = [{
"orderStatus": "S",
"x_ExtnIsModifiable": "N",
"grandTotal": "24",
"orderId": "",
"grandTotalCurrency": "USD",
"placedDate": "2015-05-11T17:56:27.406Z",
"x_ExtnIsModifiableUntil": "2012-07-24 23:59:00.0",
"externalOrderID": "29001e"
}, {
"orderStatus": "S",
"x_ExtnIsModifiable": "N",
"grandTotal": "23",
"orderId": "",
"grandTotalCurrency": "USD",
"placedDate": "2015-04-11T17:56:27.406Z",
"x_ExtnIsModifiableUntil": "2012-07-24 23:59:00.0",
"externalOrderID": "29001d"
}, {
"orderStatus": "S",
"x_ExtnIsModifiable": "N",
"grandTotal": "22",
"orderId": "",
"grandTotalCurrency": "USD",
"placedDate": "2015-03-11T17:56:27.406Z",
"x_ExtnIsModifiableUntil": "2012-07-24 23:59:00.0",
"externalOrderID": "29001c"
}];
console.log("Your order length array is: " + OrderStatusArray.length);
var data = [
{
"orderStatus":"S",
"x_ExtnIsModifiable":"N",
"grandTotal":"24",
"orderId":"",
"grandTotalCurrency":"USD",
"placedDate":"2015-05-11T17:56:27.406Z",
"x_ExtnIsModifiableUntil":"2012-07-24 23:59:00.0",
"externalOrderID":"29001e"
},
{
"orderStatus":"S",
"x_ExtnIsModifiable":"N",
"grandTotal":"23",
"orderId":"",
"grandTotalCurrency":"USD",
"placedDate":"2015-04-11T17:56:27.406Z",
"x_ExtnIsModifiableUntil":"2012-07-24 23:59:00.0",
"externalOrderID":"29001d"
},
{
"orderStatus":"S",
"x_ExtnIsModifiable":"N",
"grandTotal":"22",
"orderId":"",
"grandTotalCurrency":"USD",
"placedDate":"2015-03-11T17:56:27.406Z",
"x_ExtnIsModifiableUntil":"2012-07-24 23:59:00.0",
"externalOrderID":"29001c"
}
];
console.log( data.length );
do you want this?
node.js - Array length is not correct in javascript - Stack Overflow
jquery - Javascript : array.length returns undefined - Stack Overflow
javascript - Cannot print JSON array from ajax call using the array length - Stack Overflow
Grabbing the length of an array in json object
The variable you are trying to store is already a json encoded string. You can not stringify it again.
You can drop those ' and reformat the json, then it would be a normal json, then you can call stringify on it.
var data = {"history":[{"keyword":key,"msg":msg,"ver":ver}]};
localStorage.setItem("history", JSON.stringify(data));
To get the length of the array after retrieve:
var historydata = JSON.parse(localStorage.getItem("history"));
console.log(historydata.history.length);
You have already a JSON string. After JSON.stringify you get a string from a string.
The array size is one, because the content in one object.
var key = 'KEY', msg = 'MSG', ver = 'VER',
data = '{"history":[' + '{"keyword":"' + key + '","msg":"' + msg + '","ver":"' + ver + '"}]}',
obj = JSON.parse(data);
document.write(obj.history.length + '<br>');
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
Maybe you consider a better use of object, like an object literal:
var key = 'KEY', msg = 'MSG', ver = 'VER',
obj = { history: [{ keyword: key, msg: msg, ver: ver }] };
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
.length is a special property in Javascript arrays, which is defined as "the biggest numeric index in the array plus one" (or 2^32-1, whatever comes first). It's not "the number of elements", as the name might suggest.
When you iterate an array, either directly with for..of or map, or indirectly with e.g. JSON.stringify, JS just loops over all numbers from 0 to length - 1, and, if there's a property under this number, outputs/returns it. It doesn't look into other properties.
The length property don't work as one will expect on arrays that are hashtables or associative arrays. This property only works as one will expect on numeric indexed arrays (and normalized, i.e, without holes). But there exists a way for get the length of an associative array, first you have to get the list of keys from the associative array using Object.keys(arr) and then you can use the length property over this list (that is a normalized indexed array). Like on the next example:
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
console.log(Object.keys(arr).length);
And about this next question:
not able to get all values while doing console.log(JSON.stringify(arr))
Your arr element don't have the correct format to be a JSON. If you want it to be a JSON check the syntax on the next example:
jsonObj = {};
jsonObj[0] = {"zero": "apple"};
jsonObj[1] = {"one": "orange"};
jsonObj["fancy"] = "what?";
console.log(Object.keys(jsonObj).length);
console.log(JSON.stringify(jsonObj));
Objects don't have a .length property.
A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:
Object.keys(data).length;
If you have to support IE 8 or lower, you'll have to use a loop, instead:
var length= 0;
for(var key in data) {
if(data.hasOwnProperty(key)){
length++;
}
}
One option is:
Object.keys(myObject).length
Sadly it not works under older IE versions (under 9).
If you need that compatibility, use the painful version:
var key, count = 0;
for(key in myObject) {
if(myObject.hasOwnProperty(key)) {
count++;
}
}
My question is pretty straight forward,
I am trying to grab the lenght of an array returned by my json. However, the array could be possibly two different names (for example orange or apple)
so how would I write code that would just grab the array length regardless of the array name
JavaScript doesn't have a .length property for objects. If you want to work it out, you have to manually iterate through the object.
function objLength(obj){
var i=0;
for (var x in obj){
if(obj.hasOwnProperty(x)){
i++;
}
}
return i;
}
alert(objLength(JSONObject)); //returns 4
Edit:
Javascript has moved on since this was originally written, IE8 is irrelevant enough that you should feel safe in using Object.keys(JSONObject).length instead. Much cleaner.
The following is actually an array of JSON objects :
var JSONObject = [{ "name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"}, {"name":"John Johnson", "street":"Oslo West 16",
"age":33, "phone":"555 1234567" }];
So, in JavaScript length is a property of an array. And in your second case i.e.
var JSONObject = {"name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"};
the JSON object is not an array. So the length property is not available and will be undefined. So you can make it as an array as follows:
var JSONObject = [{"name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"}];
Or if you already have object say JSONObject. You can try following:
var JSONObject = {"name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"};
var jsonObjArray = []; // = new Array();
jsonObjArray.push(JSONObject);
And you do get length property.
Its not an array you need to parse it first to get as an array :
var ownAc=JSON.parse(user.ownAccount)
console.log(ownAc.length);
Use the simple method Object.keys(obj) with the reference of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
In your case the answer is Object.keys(user.ownAccount).length
var user = {
"username": "testuser update",
"email": "[email protected]",
"name": "user001",
"ownAccount": [{
"id": 2,
"name": "Demo Account2"
},
{
"id": 1,
"name": "Demo Account"
}
]
};
console.log(Object.keys(user.ownAccount).length);
This does the same think as Object.keys(obj).length, but without the browser compatibility issue (I think).
What about:
var obj = {
yo: {
a: 'foo',
b: 'bar'
}
hi: {
c: 'hello',
d: 'world',
e: 'json'
}
}
var arr = [], len;
for(key in obj) {
arr.push(key);
}
len = arr.length;
console.log(len) //2
OR
var arr = [], len;
for(key in obj.hi) {
arr.push(key);
}
len = arr.length;
console.log(len) //3
OR, in your case
var arr = [], len;
for(key in studentMockBeanMap) {
arr.push(key);
}
len = arr.length;
console.log(len); //4
You can also use the lodash library (which has a size function).
http://lodash.com/docs#size
_.size({red: 'red', blue: 'blue'}) // 2
Before going to answer read this Documentation once. Then you clearly understand the answer.
Try this It may work for you.
Object.keys(data.shareInfo[i]).length
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
your data is already json format:do like this
var App = [
{
"id": "123",
"caption": "Test",
"description": "Test Desc"
},
{
"id": "345",
"caption": "adsasdasd",
"description": ""
},
{
"id": "456",
"caption": "adsasdasd",
"description": ""
},
{
"id": "578",
"caption": "adsasdasd",
"description": ""
}
];
console.log(App);
console.log(App[0].length);// you can not get length from this because it is not array it's an object now.
var AppLen = App.length;
alert(AppLen);
obj.size() or obj.length
If that dont run try this: Length of a JavaScript object
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(myArray);
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.lengthwill 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
Try this, there is a correction in your code. You're not pushing IDs into an array but you're assigning a new value of IDs every time.
it('gets person id in array',()=>{
let array_ids =[];
let count=0;
return response.then((api_response)=>{
for(var i=1;i<api_response.body.length;i++){
//this is correctly printing the person id of response
console.log('Person ids are ==>'+api_response.body[i].person_id);
count++;
//this is not working
array_ids.push(api_response.body[i].person_id); //update
}
console.log('Count is '+count) //prints correct number
console.log('Array length '+array_ids.length) //prints incorrect length - sometimes 11, sometimes 12
});
});
You need to push ids into array
array_ids.push(api_response.body[i].person_id);
You can use Array.prototype.map()
let array_ids = api_response.body.map(obj => obj.person_id);
let count = array_ids.length;
You should do something like:
$.getJSON('fresh_posts.php',function(data){
global_save_json = data.freshcomments;
var countPosts = Object.keys(data.freshposts).length;
});
"freshposts" is not an array it's an object:
"freshposts": { ... }
It should look like this:
"freshposts": [ ... ]
I think you have a misunderstanding of what JSON is. JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you want is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.
It seems like whatever you are using to make the HTTP request is auto parsing the JSON response into a POJO on some browsers and not on others.
var json = '[{"url":"http://google.com"},{"url":"http://yahoo.com"}]';
json.length // 56 (this is the character count since json is a string)
var obj = JSON.parse(json);
obj.length // 2 (since there are two items in the array
obj[0].url // 'http://google.com'
UPDATE: after discussion with OP, his issue was lack of support for responseType in his XMLHttpRequest handler (it's a level 2 enhancement where as the browsers in question only support level 1). Added the following check to see if the response was auto-parsed to an object and if not do it manually:
var obj = typeof xhr.response === 'string' ? JSON.parse(xhr.response) : xhr.response;
Use concat instead of push, because you add one array to another
Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:
[
"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
]
Then, you can get a javascript array as follows:
var array = JSON.parse(jax.responseText);
And access values as follows:
array[0]
array.length
EDIT: In order to have a real JSON array with the PHP json_encode method, see this related question.
With this modification you will be able to use all the possibilities of JS array without workaround.
Objects in JavaScript don't have a .length property like Arrays do.
In ES5 you can do: Object.keys({}).length; // 0
The other solution would be to loop over all the properties of your object with a for .. in loop and count.