Nick Myers Nick Myers - 1 year ago 81
Javascript Question

Counting elements in JSON using JavaScript

I hope someone can point me in the right direction, I've burnt hours trying to solve what I think is a simple problem - I've hunted SO and tried various things that were close but no cigar.

I want to count two things from the sample JSON block below.

First I want to count the number of productLine entries, and second I want to count the number of types - by productLine and in total across all productLine(s).

So I'd like to end up with 3 variables with a number assigned to them to represent these three values.

Is anyone able to help?

var products =
"product" : "Product Name",
"productLines": [
"productLine" : "Line 1",
"types": ["Type 1", "Type 2", "Type 3", "Type 4"]
"productLine": "Line 2",
"types": ["Type 5", "Type 6", "Type 7", "Type 8"]
"productLine": "Line 3",
"types": ["Type 9", "Type 10", "Type 11"]
"productLine": "Line 4",
"type": ["Type 12", "Type 13"]

Output would be something like:

var productLineCount = 4
var productLine[0].name = "Line 1"
var productLine[0].types.count() = 4
var typesCount = 13

Answer Source

You can do it by,

var prodLines = products.productLines.length;
var prodLinesTypes = products.productLines.reduce(function(a,b){ 
       return a + (b.types.length) 
}, 0);

console.log(prodLines); //4
console.log(prodLinesTypes); //13

The first one is an obvious one, that is reading the length of an array. But the second one can be done by using .reduce(). It can be done in many ways. But I would suggest you to go with reduce at this context.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download