【问题标题】:In NodeJS, convert database query output to Json format在 NodeJS 中,将数据库查询输出转换为 Json 格式
【发布时间】:2018-05-27 20:44:18
【问题描述】:

这是我的代码:

oracledb.getConnection(
  {
    user          : "user",
    password      : "password",
    connectString : "gtmachine:1521/sde1"
  },
  function(err, connection)
  {
    if (err) { console.error(err); return; }
    connection.execute(
      "SELECT filetype, filetypeid from filetype where filetypeid < 6",
      function(err, result)
      {
        if (err) { console.error(err); return; }
         response =  result.rows;
         console.log(response);
         res.end(JSON.stringify(response));
      });

这是输出

[["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]]

但我的前端 angularjs 期待这种格式的东西:

[{"filetype":"Ascii Text","filetypeid":1},{"filetype":"Binary","filetypeid":2}]

有谁知道转换它的标准方法是什么?

【问题讨论】:

    标签: angularjs json node.js


    【解决方案1】:

    这些会将您的数组数组转换为对象数组:

    var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
    
    results = results.map(
      function(item) {
        return {
          filetype: item[0],
          filetypeid: item[1]
        }
      }
    );
    
    console.log(results);

    在 ES6 中:

    var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
    
    results = results.map(item => ({filetype: item[0], filetypeid: item[1]}));
    
    console.log(results);

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 2020-05-11
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多