Hi!
I'm creating a warn system and I want to save warns to JSON file. The problem is that when I'm trying to make a new object in something it overwrites.
My code:
const warnObject = JSON.parse(fs.readFileSync('./data/data.json'));
const id = "739176"
const length = Object.keys(warnObject[id]).length + 1
warnObject[id] = {}
warnObject[id][length] = {}
warnObject[id][length]["reason"] = "This is a reason."
warnObject[id][length]["date"] = new Date().toLocaleString();
fs.writeFileSync('./data/data.json', JSON.stringify(warnObject));
And here's my JSON file:
{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}
So I want to instead of overwriting warn number 2 create new like this
{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}, {"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}
If you want to have multiple warning objects under the id "739176", you would need to format your json file in order to have an array associated to your id, such as :
{
"739176":[
{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}},
{"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}
]
}
So, once you have formatted your file this way, you will be able to get the array referred by the id, and push objects to it like this :
warnObject[id].push({"4":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}});