Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!