4

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.

DisplayName
  • 3,093
  • 5
  • 35
  • 42
msg
  • 1,480
  • 3
  • 18
  • 27

3 Answers3

4
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

c.P.u1
  • 16,664
  • 6
  • 46
  • 41
  • Thanks for the help @c.P.u1. And is it possible to count depending on particular array names. – msg Jul 25 '13 at 13:12
  • That doesn't work in old IE; if all you serve is mobile and new browsers that may be fine. – frenchie Jul 25 '13 at 13:31
  • @user2546074, the key parameter in `filter` holds the name of the property. For e.g., if you wanted a count of arrays with name 'OtherName': `return data[key] instanceof Array && key === 'OtherName'` – c.P.u1 Jul 25 '13 at 15:09
1

I'd write something to count all the types

var obj = {
    k1: ['a','b'], k2: ['cd','ef'],
    k3: 0, k4: 1,
    k5: {a:'b'},
    k6: new Date(),
    k7: "foo"
};

function getType(obj) {
    var type = Object.prototype.toString.call(obj).slice(8, -1);
    if (type === 'Object') return obj.constructor.name;
    return type;
}

function countTypes(obj) {
    var k, hop = Object.prototype.hasOwnProperty,
        ret = {}, type;
    for (k in obj) if (hop.call(obj, k)) {
        type = getType(obj[k]);
        if (!ret[type]) ret[type] = 1;
        else ++ret[type];
    }
    return ret;
}

var theTypes = countTypes(obj);
// Object {Array: 2, Number: 2, Object: 1, Date: 1, String: 1}

Now if I wanted to know the number of Arrays only

var numArrays = theTypes.Array || 0; // 2 Arrays in this example
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

You could try checking the type of each member of your object.

var count = 0;
for (var foo in mainobject) {
    if (foo instanceof Array) count++;
}

Now all you have to do is read the value of count.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62