Boninseg Boninseg - 2 months ago 6
JSON Question

Search for a related json data

How can i find data that is related to the already known data?
( I'm a newb. )

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 that
"log"
is
1
and i want to find out the data
"pass"
that is related to it.

i've tried to do it so :

The POST request comes with
log
and
pass
data , i search the .json file for the same
log
value and if there is the same data then i search for related
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");

});


The problem is that when i use

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


it searches through the whole .json file and not through only one objekt.

Answer

Your main problem is that .some() returns a boolean, whether any of the elements match your predicate or not, but not the element itself.

You want .find() (which will find and return the first element matching the predicate):

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

Note that it is possible for .find() to not find anything, in which case it returns undefined.