如何为 NodeJS 创建一个返回带有动态键名的数组的函数?

发布于 2024-12-17 07:06:53 字数 1875 浏览 0 评论 0原文

我正在开发一个使用 NodeJS、express、express-resource 和 Sequelize for MySQL ORM 构建的 RESTful api。我希望能够检索一组记录并使用 res.json(records) 进行响应。但是,我无法直接使用sequelize返回的集合。当我尝试时,出现以下错误:

类型错误:将循环结构转换为 JSON

作为解决方法,我创建了一个函数,该函数接受记录输入并返回一个数组:

/**
 * takes an Array of records and 
 * returns a collection
 *
 * @param {Array} recs
 * @return {Array}
 * @api public
 */
function recs2Array(recs){
    for(var c = 0; c < recs.length; c++){
        var collection = [];
        (function(c){
            // this is crap and must be done for every query
            var data = {
                id: recs[c]['id'],
                gender: recs[c]['gender']
            };
            collection.push(data);
            // debugger;
        })(c);
    };
    return collection;
};

现在,这效率非常低,因为我必须手动定义要返回的所有数组键。这意味着我必须在我想要 res.json() 的每个 model.find() 或 model.findAll() 的地方使用此模式。在我的一个资源控制器中,我必须对多个集合执行此操作,从而产生大量额外代码。

为了使这一点更好,我正在尝试创建一个将动态生成数组键的函数:

/**
 * takes an Array of records
 * and and Array of fields and returns 
 * a collection.
 *
 * @param {Array} recs
 * @param {Array} fields
 * @return {Array}
 * @api public
 */
function recs2ray(recs, fields){
    for(var c = 0; c < recs.length; c++){
        fields = fields || null;
        var collection = [];
        (function(c){
            for(var i = 0; i < fields.length; i++){
                (function(i){
                    // how do I create dynamic,
                    // variable key names?
                })(i);
            }
            debugger;
        }
    };
};

不幸的是,我不太确定如何制作动态数组键。我想我会传入一个预定义的数组,其中包含将在函数调用中映射的字段:

var recs = recs2Array(genders, {['id', 'gender']});

当我这样做时,我感觉在某种意义上破坏了续集 ORM。所以,我的问题是,“如何将sequelize的 model.findAll() 返回的数组中的字段动态映射到推送到返回给调用者的集合中的数组?”

I'm working on a RESTful api built with NodeJS, express, express-resource, and sequelize for MySQL ORM. I want to be able to retrieve a set of records and respond with res.json(records). However, I am unable to directly use the collection returned by sequelize. When I try, I get the following error:

TypeError: Converting circular structure to JSON

As a work around, I created a function that takes the records input and returns an array:

/**
 * takes an Array of records and 
 * returns a collection
 *
 * @param {Array} recs
 * @return {Array}
 * @api public
 */
function recs2Array(recs){
    for(var c = 0; c < recs.length; c++){
        var collection = [];
        (function(c){
            // this is crap and must be done for every query
            var data = {
                id: recs[c]['id'],
                gender: recs[c]['gender']
            };
            collection.push(data);
            // debugger;
        })(c);
    };
    return collection;
};

Now, this is terribly inefficient because I have to manually define all of the array keys that are to be returned. This means I have to use this pattern everywhere I want to res.json() for each model.find() of model.findAll(). In one of my resource controllers I have to do this for multiple collections resulting lots of extra code.

To make this better, I'm trying to create a function that will generate the array keys dynamically:

/**
 * takes an Array of records
 * and and Array of fields and returns 
 * a collection.
 *
 * @param {Array} recs
 * @param {Array} fields
 * @return {Array}
 * @api public
 */
function recs2ray(recs, fields){
    for(var c = 0; c < recs.length; c++){
        fields = fields || null;
        var collection = [];
        (function(c){
            for(var i = 0; i < fields.length; i++){
                (function(i){
                    // how do I create dynamic,
                    // variable key names?
                })(i);
            }
            debugger;
        }
    };
};

Unfortunately, I'm not really sure how to make dynamic array keys. I was thinking that I would pass in a predefined array that contains fields that will be mapped in the function call:

var recs = recs2Array(genders, {['id', 'gender']});

When I do this I get the feeling am undermining sequelize ORM in some sense. So, My question is, "How can I dynamically map fields from the array that is returned by sequelize's model.findAll() to an array that is pushed to a collection that is returned to the caller?"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

大姐,你呐 2024-12-24 07:06:53
var input = ...;
var result = input.map(function(row) {
  var result = {};
  ['id', 'gender'].forEach(function(key) {
    result[key] = row[key];
  });
  return result;
});

或者,如果您想使用辅助方法来完成此操作:

function purify(obj, keys) {
  return obj.map(function(row) {
    var result = {};
    keys.forEach(function(key) {
      result[key] = row[key];
    });
    return result;
  });
}
var result = purify(..., ['id', 'gender']);
var input = ...;
var result = input.map(function(row) {
  var result = {};
  ['id', 'gender'].forEach(function(key) {
    result[key] = row[key];
  });
  return result;
});

Or if you want to do it with a helper method:

function purify(obj, keys) {
  return obj.map(function(row) {
    var result = {};
    keys.forEach(function(key) {
      result[key] = row[key];
    });
    return result;
  });
}
var result = purify(..., ['id', 'gender']);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文