简体   繁体   English

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

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

Is there any way, how to iterate over object which we got in controller by @Query() anotations? 有没有办法,如何通过@Query() anotations迭代我们在控制器中得到的对象?

We have dynamic count and name of query parameters in GET, so we need to take whole @Query() object and iterate over them to know what paramas we exactly have. 我们在GET中有动态计数和查询参数的名称,因此我们需要获取整个@Query()对象并迭代它们以了解我们确切拥有的paramas。

But if I want to iterate over that object I got error that object is not iterable. 但是,如果我想迭代该对象,我得到的错误是该对象不可迭代。

Any idea how to do that? 知道怎么做吗?

You can use Object.keys() to get an array of the keys of the query object. 您可以使用Object.keys()来获取查询对象的键的数组。 You can then iterate over this array of keys: 然后,您可以遍历此数组键:

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

In nest controller, use @Query() / @Body() / @Headers() decorator without argument will return a key-value javascript object. 在nest控制器中,使用@Query() / @Body() / @Headers()装饰器而不带参数将返回一个键值javascript对象。

for example: 例如:

    // 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 ...
    }

reference: 参考:

Object 宾语

Object.keys() Object.keys()

Object.values() Object.values()

Object.entries() 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