[英]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 ...
}
參考:
// 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.