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

133
Vistas
Add new object to JSON automatically

So basically, I'm working on this project for frontendmentor and I wanted to go a bit further and make it so this shows stored tasks as well as add new ones.

// JSON.data
[
    {
        "name": "task1",
        "todo": "Complete online Javascript course"
    },
    {
        "name": "task2",
        "todo": "Jog around the park 3x"
    }
]
// Script
getData = () => {
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status ==200) {
            const myData = JSON.parse(this.responseText)
            dataUse(myData)
            saveData(myData)
        }
    }
    xhttp.open("GET", "data.json", true);
    xhttp.send();
}

dataUse = (object) =>{
    object.forEach((datas)=>{
        const todo = document.createElement('div')
        todos.appendChild(todo)

        const input = document.createElement('input')
        input.setAttribute('type', 'checkbox')
        input.setAttribute('id', datas.name)
        input.setAttribute('class', 'checks')
        todo.appendChild(input)
        
        const label = document.createElement('label')
        label.setAttribute('for', datas.name)
        label.setAttribute('class', `${datas.name} tasks`)
        todo.appendChild(label)
        
        const span = document.createElement('span')
        label.appendChild(span)
        
        const paragraph = document.createElement('p')
        paragraph.innerHTML = datas.todo
        label.appendChild(paragraph)
    })
}

getData()

Currently the code above loads the data and then proceeds to make the element needed and place the info in the right place.

What I need now is to make it so it saves a new object to JSON file (when the input has a value(I think I can figure this part myself)) automatically and then proceeds to show it just like the dataUse function does. This is what I tried to do:

let newData = {
    name: "task3",
    todo: "Water the plants"
}

const fs = require('fs')

const saveData = (object) =>{
    const finished = (error)=>{
        if(error){
            console.error(error);
            return
        }
    }

    object.push(newData)

    const jsonData = JSON.stringify(object, null, 2)
    fs.writeFile('data.json', jsonData, finished)
}

This doesn't seem to work but when I try pushing the newData without attempting to rewrite the file and console.log it it does show all the objects including the new one. So how do I make this work? or is there a better way to do this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think what you are looking for is fs.appendFile

fs.appendFile("data.json", jsonData, finished);

I have a repo that uses this general format for reference: https://github.com/cireneirbo/iCanRead-iCanWrite-imFS/blob/main/main.js

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