简体   繁体   English

JSON / Javascript-如何从文本文件中检索数据并将其存储到数组中

[英]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. 对于从.txt文件中适当地检索某些数据并将其适当地使用JSON或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. 存储的数据包含用户名/密码,我想在其中创建一些javascript函数来读写.txt文件,但这样做有很大困难。 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. 我一直在尝试找出如何逐行搜索的方法,首先要使用户名/密码与输入字段匹配,然后再添加到这些数组中(然后再允许将它们添加到.txt文件中),但到目前为止还没有成功。 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) JSON数组(文本文件数据)

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

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: 请注意,数组过滤器返回匹配项的LIST,因此您需要为匹配的用户选择第一个:

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 在此处查看代码: https//plnkr.co/edit/xBM2U9MHsgrxkqvEa7Gz?p = preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM