打字稿通过包含特殊字符的键从数组中删除项目

时间:2021-07-22 06:36:27

标签: angular 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] 删除此参数?

1 个答案:

答案 0 :(得分:2)

您可以使用 [] 访问要删除的密钥,并使用 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 规范中详细介绍了这一点:4.13 Property Access


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" } 

Link to TS Playground