简体   繁体   English

Javascript(node.js)数组转换为特定的字符串格式(类似于JSON)

[英]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. 我在网上进行的所有挖掘和搜索操作均未找到正确的方法来以所需的格式获取以下字符串,我当然可以以粗略的方式进行连接和实现,但是我渴望学习Javascript + JSON。 I'm using the string in node.js express basic authentication. 我正在使用node.js中的字符串表示基本身份验证。

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'}

userList should be an object userList应该是一个对象

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

Alternatively, you can use Array.reduce 或者,您可以使用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)); 

This is the appropriate time to use reduce : 这是使用reduce的适当时间:

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

Using userList as an object is the correct way. 使用userList作为对象是正确的方法。 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: 但是,如果您已经有了一个数组,并且必须将其转换为对象,将元素2乘2,则可以使用以下函数:

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

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

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