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

142
Visualizações
To find match element in array json.file and change it [node js]

Good afternoon, I have a script that changes the value of the json file

const fsp = require('fs').promises;

async function udpateTimeInFile() {
    try {
        let data = await fsp.readFile('example.json');
        let obj = JSON.parse(data);

        obj.number = 777;

        await fsp.writeFile('example.json', JSON.stringify(obj));
    } catch(e) {
        console.log(e);
    }
}
udpateTimeInFile();

I need the script to find the first number 2 in the array and object numbers and change the unit to 3 and my json

{
  "foods": 111,
  "numbers": [1, 27, 5, 7, 0, 0, 2, 0, 0],
  "surnames": [1, 1, 1, 1, 1, 1, 1, 1, 1],
  "date": 0
}

And after execution js application the file would become like this

{
  "foods": 111,
  "numbers": [1, 27, 5, 7, 0, 0, 3, 0, 0],
  "surnames": [1, 1, 1, 1, 1, 1, 1, 1, 1],
  "date": 0
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the Array#findIndex method to find the index of the first occurrence of 2, then you can use the index to change the value to 3.

DEMO

const obj = {
  "foods": 111,
  "numbers": [1, 27, 5, 7, 0, 0, 2, 0, 0],
  "surnames": [1, 1, 1, 1, 1, 1, 1, 1, 1],
  "date": 0
},

i = obj.numbers.findIndex(num => num === 2);

if (i > -1) {
    obj.numbers[i] = 3;
}

console.log( obj );

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