Home > other >  JSON array, javascript count [duplicate]
JSON array, javascript count [duplicate]

Time:10-09

I have a JSON array in a local file called data.json, looks the following:

[
    {
        "id":"1",
        "priority": "P1",
        "start_date": "2021-01-01 14:40:33"
    },{
        "id":"2",
        "priority": "P2",
        "start_date": "2019-01-01 14:40:33"
    },{
        "id":"3",
        "priority": "P3",
        "start_date": "2020-01-01 14:40:33"
    },{
        "id":"4",
        "priority": "P2",
        "start_date": "2020-01-01 14:40:33"
    },{
        "id":"5",
        "priority": "P1",
        "start_date": "2021-01-01 14:40:33"
    }
]

I'm trying to get total count set by two conditions as seen below, however the formatting on the start_date YYYY-MM-DD HH-MM-SS is static and can't be changed, I want to be able to look for the first 4 digits only (the year) but still unable to, any toughts?

import data from "./data.json" assert{ type: "json" };

    var count = 0;
    for (var i = 0; i < data.length; i  ) {
        if ((data[i].priority === 'P1') && (data[i].start_date === "2021")) {
            count  ;
        }
    }
    console.log(count)

CodePudding user response:

What about instead using String.prototype.startsWith:

import data from "./data.json";

let count = 0;

for (let i = 0; i < data.length; i  ) {
  if (data[i].priority === "P1" && data[i].start_date.startsWith("2021")) {
    count  ;
  }
}

console.log(count);

You could also try instead using Array.prototype.filter:

const count = data.filter(
  item => item.priority === "P1" && item.start_date.startsWith("2021")
).length;
   

Or with destructuring:

const count = data.filter(
  ({ priority, start_date }) =>
    priority === "P1" && start_date.startsWith("2021")
).length;
  • Related