Jordy
Jordy

Reputation: 217

JSON/Javascript - How to retrieve data from a text file and store it into an array

just having a bit of an issue with a group assessment regarding appropriately retrieving some data from a .txt file and appropriately storing it into an array using JSON or Javascript. The stored data is contains username/passwords, in which i want to create some javascript functions to read/write to and from the .txt file, but I'm having immense difficulty doing so. I've been trying to figure out how to search line by line to first of all match the user/password with inputted fields, and then additionally add to these arrays (and then furthermore allowing them to be added to the .txt file), but have had no success so far. I know it's a long-winded question, but any help/resources would be really appreciated that would relate to what I'm trying to do.

JSON array (text file data)

myObj = {
        "users": [
            { "name":"John", "password":"test123" },
            { "name":"Cindy", "password":"apples22" },
            { "name":"Phil", "password":"oranges64" }
        ]
     }

Upvotes: 0

Views: 112

Answers (1)

VSO
VSO

Reputation: 12646

Use the array filter method:

You can select the user from the array like so (by either name or pass, I am using pass):

var matchingUsers = users.filter(u => u.name === name);

Note that array filter returns a LIST of matches, so you need to select the first one for the matching user:

var singleMatchingUser = matchingUsers[0];

If you expect duplicate names, you need to account for that.

All relevant code here:

myObjAsJson = {
  "users": [
    {"name":"John", "password":"test123"},
    {"name":"Cindy", "password":"apples22"},
    {"name":"Phil", "password":"oranges64"}
  ]
}

function findPassByName(users, name) {
  var matchingUsers = users.filter(u => u.name === name);
  return matchingUsers[0].password;
}

var cindysPass = findPassByName(myObjAsJson.users, 'Cindy');

console.log(cindysPass); //This logs 'apples22'

See code here: https://plnkr.co/edit/xBM2U9MHsgrxkqvEa7Gz?p=preview

Upvotes: 1

Related Questions