繁体   English   中英

如何在Nest js中迭代@Query()对象

[英]How to iterate over @Query() object in Nest js

有没有办法,如何通过@Query() anotations迭代我们在控制器中得到的对象?

我们在GET中有动态计数和查询参数的名称,因此我们需要获取整个@Query()对象并迭代它们以了解我们确切拥有的paramas。

但是,如果我想迭代该对象,我得到的错误是该对象不可迭代。

知道怎么做吗?

您可以使用Object.keys()来获取查询对象的键的数组。 然后,您可以遍历此数组键:

@Get()
getHello(@Query() query) {
  for (const queryKey of Object.keys(query)) {
    console.log(`${queryKey}: ${query[queryKey]}`);
  }
}

在nest控制器中,使用@Query() / @Body() / @Headers()装饰器而不带参数将返回一个键值javascript对象。

例如:

    // request url: http://example.com/path-foo/path-bar?qf=1&qb=2

    @Post(':foo/:bar')
    async function baz(@Query() query,@Param() param) {
        const keys = Object.keys(query); // ['qf', 'qb']
        const vals = Object.values(query); // ['1', '2']
        const pairs = Object.entries(query); // [['qf','1'],['qb','2']]
        const params = Object.entries(param); // [['foo','path-foo'],['bar','path-bar']]
        // these are all iterate able array
        // so you can use any Array's built-in function
        // e.g. for / forEach / map / filter ...
    }

参考:

宾语

Object.keys()

Object.values()

Object.entries()

    // sample object
    const obj = {
      foo: 'this is foo',
      bar: 'this is bar',
      baz: 'this is baz',
    };

    Object.keys(obj);
    Object.values(obj);
    Object.entries(obj);

    /**
     * return iterable array:
     *
     * ['foo', 'bar', 'baz']
     *
     * ['this is foo', 'this is bar', 'this is baz']
     *
     * [
     *     ['foo', 'this is foo']
     *     ['bar', 'this is bar']
     *     ['baz', 'this is baz']
     * ]
     */

暂无
暂无

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

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