-2

I have the following file "data.JSON" and I wish to loop through the JSON file and filter data based on dates. For example

data.JSON:

[{"EngComment":"test, <br> <br>5/10/2021 6:33:6 luisdomi"},
{"EngComment":" "},
{"EngComment":" "},
{"EngComment":"test, <br> <br>5/25/2021 17:24:20 luisdomi"},
{"EngComment":" "}
]

I am kind of new to Java Script and also have trouble declaring it on a separate script file

var json = data.json

for(var i = 0; i < json.length; i++) {
    var obj = json[i];
    
    if(timenow - obj <72 hours){
      json[i] = ""

    }
}

//save the file if possible

so the new JSON file is now:

[{"EngComment":""},
{"EngComment":" "},
{"EngComment":" "},
{"EngComment":""},
{"EngComment":" "}
]
  • So in addition to making your script work you need to import this from another file? What research have you done? I see you have a pseudo script there, that is a start. Have you looked into how to load a JSON file? We need to see that you've done your research and help guide you from there. – Kinglish Jun 18 '21 at 21:05

1 Answers1

1

If I could understand your problem you need a comparison between current date and the dates inside your json, if it less than 72 hrs then json data should be set to blank.

First you need to extract date from the json value for each item after wards compare it. Below could be the solution you are looking for.

let json = [
    { "EngComment": "test, <br> <br>5/10/2021 6:33:6 luisdomi" },
    { "EngComment": " " },
    { "EngComment": " " },
    { "EngComment": "test, <br> <br>6/18/2021 17:24:20 luisdomi" },
    { "EngComment": " " }
]

for (var i = 0; i < json.length; i++) {
    var date = json[i].EngComment.substring(15, 32)
    let time = new Date().getTime() - new Date(date).getTime()

    if (Math.abs(time) / (1000 * 60 * 60) < 72) {
        json[i] = ""
    }
}
console.log(json)

To save this json into the file you can use fs library.

bhaginath
  • 456
  • 4
  • 13