3

All my digging and searching online did not result to find me right method to get the following string in required format, I can of course concatenate and achieve this in crude way, however I'm eager to learn Javascript + JSON. I'm using the string in node.js express basic authentication.

I need to build the following string (the one only inside the curly braces):

app.use(basicAuth(...
  users: { 'admin': 'adminpass' , 'user':'userpass'},.....

Code to fetch the data from database:

connection.query('SELECT * FROM wts_users', function (error, results, fields) {
  if (error) throw error;
  for (var i = 0; i < results.length; i++) {
    var result = results[i];
    userList.push(result.user_name, result.user_password)
  }
  console.log("user list: "+JSON.stringify(userList));
});

The result I'm getting:

["admin","adminpass","user","userpass"]

How can I get the result in the below format.

{ 'admin': 'adminpass' , 'user':'userpass'}

3 Answers 3

3

userList should be an object

userList = {};
userList[result.user_name] = result.user_password;

Alternatively, you can use Array.reduce

let results = [{user_name: "admin", user_password : "adminpass"}, {user_name: "user", user_password : "userpass"}]

let userList = results.reduce((o, {user_name, user_password}) => Object.assign(o, {[user_name] : user_password}), {});

console.log("user list: "+JSON.stringify(userList));

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

Comments

1

Using userList as an object is the correct way. But if you already have an array and must necessarily convert it into an object, taking elements 2 by 2, you may use this function:

function toObject(arr) {
  var obj = {};
  for (var i = 0; i < arr.length; i+=2)
    obj[arr[i]] = arr[i+1];
  return obj;
}

Demo

let result = ["admin","adminpass","user","userpass"]

function toObject(arr) {
  var obj = {};
  for (var i = 0; i < arr.length; i+=2)
    obj[arr[i]] = arr[i+1];
  return obj;
}

console.log(toObject(result));

Comments

1

This is the appropriate time to use reduce:

const userList = results.reduce((a, { user_name, user_password }) => {
  a[user_name] = user_password;
  return a;
}, {});

Comments

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.