用字符串而不是对象对返回数组进行续集

Sequelize return array with Strings instead of Objects(用字符串而不是对象对返回数组进行续集)
本文介绍了用字符串而不是对象对返回数组进行续集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我只想从多行中选择一个值.

Sometimes i only want to select a single value from multiple rows.

假设我有一个如下所示的帐户模型:

Lets imagine i have an account model which looks like this:

帐户

  • 身份证
  • 姓名
  • 年龄

我只想选择名字.

你会这样写:

AccountModel.findAll({
        where: {
            Age: {
                $gt : 18
            }
        },
        attributes: ['Name'],
        raw : true
    });

但这会返回一个带有对象的数组.

But this would return in an array with objects.

[{Name : "Sample 1"}, {"Name" : "Sample 2"}]

我想得到一个只有这样名字的数组:

I would like to get an array with only names like this:

["Sample 1", "Sample 2"]

是否可以通过 Sequelize 实现这一目标?我已经搜索了文档但找不到它.

Is it possible to achieve this with Sequelize? I've searched trough the documentation but couldn't find it.

推荐答案

使用 Sequelize 3.13.0 似乎不可能让 find 返回一个平面数组而不是数组对象.

Using Sequelize 3.13.0 it looks like it isn't possible to have find return a flat array of values rather than an array of objects.

解决问题的一种方法是使用下划线或 lodash 映射结果:

One solution to your problem is to map the results using underscore or lodash:

AccountModel.findAll({
    where: {
        Age: {
            $gt : 18
        }
    },
    attributes: ['Name'],
    raw : true
})
.then(function(accounts) {
  return _.map(accounts, function(account) { return account.Name; })
})

我已经上传了一个脚本来演示这个 这里.

I've uploaded a script that demonstrates this here.

作为快速说明,设置 raw: true 会使 Sequelize 查找方法返回普通的旧 JavaScript 对象(即没有实例方法或元数据).这可能对性能很重要,但不会更改转换为 JSON 后的返回值.这是因为 Instance::toJSON 总是返回一个普通的JavaScript 对象(无实例方法或元数据).

As a quick note, setting raw: true makes the Sequelize find methods return plain old JavaScript objects (i.e. no Instance methods or metadata). This may be important for performance, but does not change the returned values after conversion to JSON. That is because Instance::toJSON always returns a plain JavaScript object (no Instance methods or metadata).

这篇关于用字符串而不是对象对返回数组进行续集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)