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



有什么办法,如何迭代我们通过@Query() Anotations在控制器中获得的对象?

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

但是,如果我想迭代该对象,我会发现对象是不可能的错误。

任何想法如何做?

您可以使用 Object.keys()获取查询对象的键。然后,您可以在此键上迭代:

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

在巢控制器中,使用@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']
     * ]
     */

最新更新