1

Hi I have JSON file that have users nickname, password and token. I'm using a find function to find users from their nicknames. I want to get tokens too.

[
  {
    "user": [
      "bombali",
      "reYiz_2031",
      "GcjSdUMp"
    ]
  },
  {
    "user": [
      "johndoe",
      "testpasswd1_s",
      "SdNFccRT"
    ]
  }
]

This is my JSON data file.

I'm checking if nicname is taken or not using this code:

function isUsernameTaken(username) {
  const user_Database = require(`${config.path_users}`);
  const finded_Name = user_Database.find(
    ({ user }) => user[0] === username.toLowerCase()
  );
  if (finded_Name === undefined) {
    console.log("This username is usable");
  } else {
    console.log("This username is unusable");
  }
}

Now I want to get token from json by using username and password to use filter. I don't want to use token:SdNFccRT in array. Is it possible? Thanks for all replies.

0

1 Answer 1

1

Using .filter() isn't the best choice in this case. With .find(), the search will stop once one element has been found, but .filter() will keep on going when it doesn't have to.

Given the username and password, you can find the token with a single .find() statement that compares each user object's username and password, then returns the token of the match. You can also use optional chaining to return undefined if no match is found. Like this:

const getToken = (data, uname, pass) => data.find(({user}) => user[0] === uname && user[1] === pass)?.user[2];

const data = [{
    "user": [
      "bombali",
      "reYiz_2031",
      "GcjSdUMp"
    ]
  },
  {
    "user": [
      "johndoe",
      "testpasswd1_s",
      "SdNFccRT"
    ]
  }
];

console.log(getToken(data, 'bombali', 'reYiz_2031'));
console.log(getToken(data, 'none', 'none'));

Sign up to request clarification or add additional context in comments.

1 Comment

You're rock mate. Thanks a lot. I'm trying to make ExpressJS like library using freeBSD licence to publish as freeware to everyone. This gonna help a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.