[英]Fetch models from JSON.file and store it localstorage Backbone
[英]To find match element in array json.file and change it [node js]
下午好,我有一个脚本可以改变 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();
我需要脚本在数组和对象编号中找到第一个数字 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
}
在执行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
}
您可以使用Array#findIndex
方法找到第一次出现2
的索引,然后可以使用索引将值更改为3
。
演示
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.