Home > Software engineering >  How to get N index of array from JSON arrays
How to get N index of array from JSON arrays

Time:01-30

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.

CodePudding user response:

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

  • Related