最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to iterate over @Query() object in Nest js - Stack Overflow

programmeradmin3浏览0评论

Is there any way, how to iterate over object which we got in controller by @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.

But if I want to iterate over that object I got error that object is not iterable.

Any idea how to do that?

Is there any way, how to iterate over object which we got in controller by @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.

But if I want to iterate over that object I got error that object is not iterable.

Any idea how to do that?

Share Improve this question edited Mar 7, 2019 at 16:36 Kim Kern 60.5k20 gold badges216 silver badges213 bronze badges asked Mar 7, 2019 at 16:08 Dominik ZatloukalDominik Zatloukal 2131 gold badge4 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

You can use Object.keys() to get an array of the keys of the query object. 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.

for example:

    // request url: http://example./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.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']
     * ]
     */
发布评论

评论列表(0)

  1. 暂无评论