![](/img/trans.png)
[英]how to update json value in fs which is read from fs in javascript?
[英]Search into a json file a value with only javascript and fs
我想創建一個 javascript function 用於搜索 json 文件的 ZA8CFDE6331BD59EB2AC96F8911C4B6 值。
getByValue(value) {
//the code
}
當我調用 function 時,我需要搜索一個 json 文件(路徑是“./database/table.json”)我傳遞的值參數,並返回 ZA8CFDE6331BD59EB2AC96F8911C4B6666
一個例子:
JSON file:
{"name": "test"}
getByValue(value) {
//code for search into the file
}
//search on the json file a object value with "test"
console.log(getByValue("test"))
//expected output: "name"
你可以這樣做:
const json = { "name": "test", "name1": "test1"} const getByValue = value => { for (let key of Object.keys(json)) if (json[key] === value) return key; } //search on the json file a object value with "test" console.log(getByValue("test")) //expected output: "name"
您需要首先在 JS 環境中加載 JSON 並解析它以讀取。 在node.js
你可以做這樣的事情
const jsonFromFile = require('filepath/file.json')
讀完JSON后,只需要找到給出值的key即可。 對此有多種方法。 基本解決方案是需要遍歷 object 並找到匹配的值。 一種這樣的方法:
const findKeyBasedOnValue = (obj, value) => Object.keys(obj).find((key) => obj[key] === value) const data = {a: 'no-test', b: 'test'} console.log(findKeyBasedOnValue(data, 'test')) // b
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.