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

171
Vistas
How to sort objects into file based on date?

Title says all, i'm trying to put objects into files based on their dates. For exmaple, I have files named "May 23","May 24","May 25" ect ect. My objects (in simplest terms) looks like this:

{id: 1, mintDate: May 23},{id: 1, mintDate: May 24},{id: 1, mintDate: May 25}

Now I want to put each object, into its respective file. for example, the {id: 1, date: May 23} object should go into the "May 23" file.

What my current code does, is for each file, it puts ALL three objects into each file. In my code, i'm not sure where i need to put the conditional to check if the date of the project is ALSO the date of the file. This is what i have currently, this all works fine without error.

        for(o in collections){
            const collection = collections[o]

            fs.readFile(__dirname + "/HowIsCollections/"+collection.mintDate,'utf8',function(err,data){
                const dat = JSON.parse(data)
                const existedData = []

                for(i in dat){
                    existedData.push(JSON.stringify(dat[i]))
                }


                const project = JSON.stringify(collections)
                if(!existedData.includes(project)){ 
                    console.log("?")
                    dat.push(project)
                }
                fs.writeFileSync(__dirname + "/HowIsCollections/"+collection.mintDate,JSON.stringify(dat)) 

            }) 
        }

I tried looking at these two threads but they didnt seem to be much help. Sort array of objects by string property value and How to sort an object array by date property?

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

0

Here you go :)

const fs = require("fs")
const path = require("path")

async function main() {
    const input = [
        { id: 1, mintDate: "May 23" },
        { id: 2, mintDate: "May 24" },
        { id: 3, mintDate: "May 25" }
    ]

    for (const part of input) {
        try {
            const previousRawData = await readFileByDate({ date: part.mintDate })
            const currentData = previousRawData.length > 0 ? [...JSON.parse(previousRawData), part] : [part]

            await writeFileByDate({ date: part.mintDate, data: JSON.stringify(currentData) })
        } catch (error) {
            console.log(error)
        }
    }
}

async function readFileByDate({ date, basePath = "." }) {
    const pathOfFile = path.join(__dirname, `${basePath}/${date}.json`)
    return new Promise((resolve, reject) => {
        fs.readFile(pathOfFile, { encoding: 'utf-8' }, (err, data) => {
            if (err)
                return reject(err)
            resolve(data)
        })
    })
}

async function writeFileByDate({ date, data, basePath = "." }) {
    const pathOfFile = path.join(__dirname, `${basePath}/${date}.json`)
    return new Promise((resolve, reject) => {
        fs.writeFile(pathOfFile, data, { encoding: 'utf-8' }, err => {
            if (err)
                return reject(err)
            resolve(true)
        })
    })
}

main()
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