How to get the number of arrays from an object

I have a JSON web service in the following format.

{ Name:['a','b'], Name:['cd','ef'], Age:{...}, Address:{...} }. 

Here I have 2 arrays and 2 objects inside an object, and these (array and objects) numbers may differ. I need how can I get the number of arrays separately from the main object? There may be another way to solve my problem, but I need my code to work in a .JS file (javascript file).


When I tried:

 Object.keys(mainobject).length; 

It gives the total number of array + objects in the main object.

+4
source share
3 answers
 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 will not work in older versions of IE

jsFiddle

To make it work with browsers that don’t support it, use gaskets from MDN:

Object.keys

Array.filter

+4
source

I would write something to count all 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 only the number of arrays

 var numArrays = theTypes.Array || 0; // 2 Arrays in this example 
+1
source

You can 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 count value.

0
source

Source: https://habr.com/ru/post/1493433/


All Articles