Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda