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

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

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 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