How do I get number of arrays from an object

arrays, javascript, json, object

Solution

var data = { Name:['a','b'], OtherName:['cd','ef'], Age:{a: 12}, Address:{a: 'asdf'} }

var numberOfArrays = Object.keys(data).filter(function(key) {
    return data[key] instanceof Array; //or Array.isArray(data[key]) if the array was created in another frame
}).length;

alert(numberOfArrays);

Note: This won't work in older versions of IE

jsFiddle

To make it work with browsers that don't support it, use the shims from MDN:

Object.keys

Array.filter

Problem

I have a JSON webservice in the following format. ``` { Name:['a','b'], Name:['cd','ef'], Age:{...}, Address:{...} }. ``` Here I have 2 arrays & 2 objects inside an object and these (array & objects) numbers may vary. What I need is, how can I get the number of Arrays alone from the main Object? There may exist another way to solve my problem but I need my code to be in a .JS (javascript file). When I tried: ``` Object.keys(mainobject).length; ``` It gives total count of array + objects in main object.

Original source

Related problems