Typescript通过包含特殊字符的键从数组中移除项



我陷入了这种情况。

我有一个键为tags[$in]的数组,我想通过Angular(Typescript(中的键删除该项。

我有一个代码,我试图通过delete params?['tags[$in]'];删除它,但这是错误的,我不能使用delete params.tags[$in],因为密钥名称中有特殊字符,我也不能使用delete params['tags[$in]'],因为params可能未定义;

listSearch<T = Response<any>>(params?: { [key: string]: any }): Observable<T> {
if (params?.search == undefined){
...
}
const paramss = qs.stringify(params, { encode: false });
return this.http.get<T>(`${this.baseURL}/stores?${paramss}`, {
headers: this.http_headers,
withCredentials: true,
responseType: 'json',
});
}

变量params为:

$limit: 12
$skip: 0
status: "active"
tags[$in]: (555) ["5dcbdd558b435f0505beeaf9", "5dcbdd558b435f0505beeafa", …]
type: "branch"
__proto__: Object

那么,在代码的第3行中使用什么来通过其键tags[$in]从数组中删除此参数呢?

您可以使用[]访问要删除的密钥,并使用key in obj运算符检查其是否存在。

const params = {
'tags[$in]': '123',
'foo': 'bar'
};
console.log('tags[$in]' in params);
console.log(params);
if('tags[$in]' in params) delete params['tags[$in]'];
console.log('tags[$in]' in params);
console.log(params);

编辑:Typescript版本。TypeScript规范中的更多信息:4.13属性访问


function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key]; // Inferred type is T[K]
}
function removeProperty<T, K extends keyof T>(obj: T, key: K) {
delete obj[key]; // Inferred type is T[K]
return obj;
}
const params: { [key: string]: any } = {
$limit: 12,
$skip: 0,
status: "active",
"tags[$in]": ["5dcbdd558b435f0505beeaf9", "5dcbdd558b435f0505beeafa"],
type: "branch"
};
const tags = getProperty(params, 'tags[$in]');
console.log(tags); // => ["5dcbdd558b435f0505beeaf9", "5dcbdd558b435f0505beeafa"] 
const tagsRemoved = removeProperty(params, 'tags[$in]');
console.log(tagsRemoved); // => { "$limit": 12, "$skip": 0, "status": "active", "type": "branch" } 

链接到TS游乐场

最新更新