Skip to content
Advertisement

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
}

Advertisement

Answer

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 );
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement