Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript (node.js) array to specific string format (similar to JSON)

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'}
like image 784
Mohammed Moinuddin Waseem Avatar asked Sep 10 '26 03:09

Mohammed Moinuddin Waseem


2 Answers

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));
like image 189
Nikhil Aggarwal Avatar answered Sep 12 '26 15:09

Nikhil Aggarwal


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));
like image 34
Attersson Avatar answered Sep 12 '26 15:09

Attersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!