How To Count Object In Javascript
Here is my code, i want to count the number of objects in this. Using eval function i was able to get the elements, but don know how to count the total objects in this. Can anybody
Solution 1:
You can use length
:
obj.employees.length
Here is the JSFiddle: http://jsfiddle.net/wavXY/3/
I recommend using JSON.parse
instead of eval
. Please go through this link for more details: http://www.json.org/js.html
Solution 2:
Being a JS noob, looking at your employees array I myself wondered how it could be traversed. I experimented a little and maybe its not most efficient way but it helped me understand how to traverse and count something like this.
Here's the fiddle: http://jsfiddle.net/bSMQn/
var txt = '{"employees":[{"a": "wkn", "d": "Wipro Technologies \u2013 IT Services, Product Engineering Solutions, Technology Infrastructure Services, Business Process Outsourcing, Consulting Services", "n": "", "u": "http://wipro.com/", "t": ["outsourcing", "offshore", "india"], "dt": "2009-06-26T10:26:02Z"}, {"a": "shaktimaan", "d": "Wipro Technologies \u2013 IT Services, Product Engineering Solutions, Technology Infrastructure Services, Business Process Outsourcing, Consulting Services", "n": "Wipro Technologies is the No 1 provider of integrated business, technology and process solutions on a global delivery platform.", "u": "http://wipro.com/", "t": ["Indian", "IT", "Services", "Companies"], "dt": "2011-09-16T17:31:25Z"}, {"a": "tonemcd", "d": "Offshore Outsourcing | IT Services", "n": "", "u": "http://wipro.com/", "t": ["outsourcing", "IT"], "dt": "2007-11-04T03:53:18Z"}]}';
var obj = eval ("("+ txt +")");
var i =0;
for (;i<obj.employees.length;i++)
{
document.writeln("Employee "+ i+":<br/><br/>");
var j =0;
for(v in obj.employees[i])
{
j++;
document.writeln(v +" => "+ obj.employees[i][v] +"<br/>");
}
document.writeln("<b>Count:"+ j +"</b>");
document.writeln("<hr/><br/>");
}
Output
Employee 0:
a => wkn
d => Wipro Technologies – IT Services, Product Engineering Solutions, Technology Infrastructure Services, Business Process Outsourcing, Consulting Services
n =>
u => http://wipro.com/
t => outsourcing,offshore,india
dt => 2009-06-26T10:26:02Z
Count:6
Employee 1:
a => shaktimaan
d => Wipro Technologies – IT Services, Product Engineering Solutions, Technology Infrastructure Services, Business Process Outsourcing, Consulting Services
n => Wipro Technologies is the No 1 provider of integrated business, technology and process solutions on a global delivery platform.
u => http://wipro.com/
t => Indian,IT,Services,Companies
dt => 2011-09-16T17:31:25Z
Count:6
....etc
Hope it helps.
Post a Comment for "How To Count Object In Javascript"