Home > Software design >  How to find the number of arrays that are present in a json file in node js
How to find the number of arrays that are present in a json file in node js

Time:07-15

[
    [
        {
            "t1": "Australia",
            "t2": "Sri Lanka",
            "t1s": "364  ",
            "t2s": "554",
            "result": "Sri Lanka won by an innings and 39 runs"
        },
        {
            "t1": "Sri Lanka",
            "t2": "Australia",
            "t1s": "113",
            "t2s": "10/0",
            "result": "Australia won by 10 wickets"
        },
        
    ],
    [
        {
            "t1": "India Women",
            "t2": "Sri Lanka Women",
            "t1s": "255/9",
            "t2s": "216",
            "result": "IND Women won by 39 runs"
        },
        {
            "t1": "Sri Lanka Women",
            "t2": "India Women",
            "t1s": "173",
            "t2s": "174/0",
            "result": "IND Women won by 10 wickets (with 146 balls remaining)"
        },
        
    ],
    
]

Here is my json file which i stored it in a file name matches.json. I want to known how many arrays are present inside the parent array.I mean this:

[

   [ ],
   [ ]

]

I want to calculate this number of arrays inside my parent array here it is 2.

Thanks in advance

CodePudding user response:

You can simply log length of your array:

const myJsonArray = [
  [],
  []
];

console.log(myJsonArray.length);

CodePudding user response:

If you want to count number of arrays in the entire object tree, then

var count_arrays = 0;
const iterate = (obj) => {
  if (!obj) {
    return;
  }
  Object.keys(obj).forEach(key => {
    var value = obj[key]
    if (Array.isArray(value)) {
      count_arrays  
    }
    if (typeof obj[key] === "object") {
      iterate(obj[key])
    }
  })
}

var obj = get_data();
iterate(obj);
console.log(count_arrays);


function get_data() {
  return [
    [{
        "t1": "Australia",
        "t2": "Sri Lanka",
        "t1s": "364  ",
        "t2s": "554",
        "result": "Sri Lanka won by an innings and 39 runs"
      },
      {
        "t1": "Sri Lanka",
        "t2": "Australia",
        "t1s": "113",
        "t2s": "10/0",
        inner: [1, 2, 3],
        "result": "Australia won by 10 wickets"
      },

    ],
    [{
        "t1": "India Women",
        "t2": "Sri Lanka Women",
        "t1s": "255/9",
        "t2s": "216",
        "result": "IND Women won by 39 runs"
      },
      {
        "t1": "Sri Lanka Women",
        "t2": "India Women",
        "t1s": "173",
        "t2s": "174/0",
        "result": "IND Women won by 10 wickets (with 146 balls remaining)"
      },
    ],
  ];
}

  • Related