user1110790 user1110790 - 9 days ago 7
Javascript Question

Count the size of items in Json Array

I am constructing a JSON response as below :

{
"G5LDUHRPEEA6B-39CFBWYA": [],
"JMSK0DKOEEA0UXMY750O3W": [],
"ISVN8JF1EEAD3W398ZNOSA": [
{

"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": LA,
"hello": "OUTSIDE"

},
{

"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Chicago,
"hello": “Inside"
},
{

"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Austin,
"hello": “Inside"
}
],
"VRG0IJF1EEAD3W398ZNOSA": [{

"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Chicago,
"hello": “Inside"
},
{

"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Austin,
"hello": “Inside"
}],
"OGAESJF2EEAD3W398ZNOSA": [],
"SC9OMJF2EEAD3W398ZNOSA": []
}


I want to count the total number of items in the array , including the internal array and disregard if the internal array is empty like "SC9OMJF2EEAD3W398ZNOSA": []
I tried _.size(collection) but I need to know how to remove empty internal ones.Thanks in advance

Answer

You can use Array.prototype.reduce and loop through to sum up the lengths of the arrays - see demo below:

var object={"G5LDUHRPEEA6B-39CFBWYA":[],"JMSK0DKOEEA0UXMY750O3W":[],"ISVN8JF1EEAD3W398ZNOSA":[{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"LA","hello":"OUTSIDE"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Chicago","hello":"Inside"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Austin","hello":"Inside"}],"VRG0IJF1EEAD3W398ZNOSA":[{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Chicago","hello":"Inside"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Austin","hello":"Inside"}],"OGAESJF2EEAD3W398ZNOSA":[],"SC9OMJF2EEAD3W398ZNOSA":[]}

var result = Object.keys(object).reduce(function(p,c){
  p+= object[c].length;
  return p;
},0);


console.log(result);