Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

85
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda