Search json related data

How can I find data related to already known data? (I'm a newbie.)

For example, here is my json:

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

Now I know what "log"is 1, and I want to know the data associated with it "pass".

I tried to do it like this:

The POST request comes with data logand pass, I am looking at the .json file for the same value log, and if there is the same data, then I look for the appropriatepass

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");

            });

The problem is that when I use

var gotPass = jsonFileArr.some(function (obj) {
                 return obj.pass == pass;
                });

it scans the entire .json file, not just through the objekt object.

+4
source share
3 answers

, .some() , , - , .

.find() ( , ):

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

, .find() -, undefined.

+3

.some() , , , , . .filter():

   var jsonFileArr = JSON.parse(data);

   var log = loginData.log;

   var matchingItems = jsonFileArr.filter(function (obj) {
     return obj.log == log;
   });

   if (matchingItems.length > 0) {     // Was at least 1 found?
     var pass = matchingItems[0].pass; // The 'pass' data that comes with the first match
   } else
     console.log("error");             // no matches
+2

ES6 Array # find, , , ( )

const x = [{
  "id": "1",
  "log": "1",
  "pass": "1111"
}, {
  "id": 2,
  "log": "2",
  "pass": "2222"
}, {
  "id": 3,
  "log": "3",
  "pass": "3333"
}];
let myItem;
for (let item of x) {
  if (item.log === '1') {
    myItem = item;
    break;
  }
}
console.log(myItem);
Hide result
+1

Source: https://habr.com/ru/post/1654312/


All Articles