简体   繁体   English

在数组 json.file 中查找匹配元素并更改它 [node js]

[英]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下午好,我有一个脚本可以改变 json 文件的值

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我需要脚本在数组和对象编号中找到第一个数字 2 并将单位更改为 3 和我的 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在执行js应用程序后文件会变成这样

{
  "foods": 111,
  "numbers": [1, 27, 5, 7, 0, 0, 3, 0, 0],
  "surnames": [1, 1, 1, 1, 1, 1, 1, 1, 1],
  "date": 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 .您可以使用Array#findIndex方法找到第一次出现2的索引,然后可以使用索引将值更改为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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM