[英]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.