如何找到与已知数据相关的数据?
(我是新手。)

例如这里是我的 json :

[
{ "id": "1",  "log": "1","pass":  "1111" },
{ "id": 2,  "log": "2","pass":  "2222" },
{ "id": 3, "log": "3","pass":  "3333" }
]

现在我知道 "log"1,我想找出与之相关的数据 "pass"

我试过这样做:

POST 请求带有 logpass 数据,我在 .json 文件中搜索相同的 log 值,如果有相同的数据,则搜索相关的 pass
fs.readFile("file.json", "utf8", function (err, data) {

                var jsonFileArr = [];
                jsonFileArr = JSON.parse(data);  // Parse .json objekts

                var log = loginData.log; // The 'log' data that comes with POST request

               /* Search through .json file for the same data*/

               var gibtLog = jsonFileArr.some(function (obj) {
                 return obj.log == log;
                });


                if (gotLog) { // If there is the same 'log'

                    var pass = loginData.pass; // The 'pass' data that comes with POST request

                  var gotPass = jsonFileArr.some(function (obj) {
                    // How to change this part ?
                    return obj.pass == pass;
                });

                }
                else
                    console.log("error");

            });

问题是当我使用
var gotPass = jsonFileArr.some(function (obj) {
                 return obj.pass == pass;
                });

它搜索整个 .json 文件,而不是只搜索一个 objekt。

最佳答案

您的主要问题是 .some() 返回一个 bool 值,无论是否有任何元素与您的谓词匹配,而不是元素本身。

您需要 .find()(它将查找并返回与谓词匹配的第一个元素):

const myItem = myArray.find(item => item.log === "1"); // the first matching item
console.log(myItem.pass); // "1111"

请注意, .find() 可能找不到任何内容,在这种情况下,它会返回 undefined

关于javascript - 搜索相关的json数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39444917/

10-12 00:33
查看更多