Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
Creating new instead of overwriting

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"}}}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"}});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!