Typescript remove item from an array by key containing special character

Viewed 251

I am stuck in this situation.

I have an array with key tags[$in] and I want to delete this item by its key in Angular (Typescript).

I have a code where I was trying to delete this by delete params?['tags[$in]']; but this is error and I cannot use delete params.tags[$in] because of special characters in key name and I also cannot use delete params['tags[$in]'] because params is possibly undefined;

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',
        });
    }

variable params is:

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

So what to use in line 3 of code to delete this parameter by its key tags[$in] from an array?

1 Answers

You can use [] to access the key to delete, and check it's existence with key in obj operator.

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);

Edit: Typescript Version. More about this in the TypeScript specification: 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

Related