簡體   English   中英

在 json 文件中搜索只有 javascript 和 fs 的值

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM