Search code examples
angulartypescriptcasting

Typescript Custom Mapping to object


I am working on an Angular app where the app is mapping the response from

return this.http.get(this.url)
      .toPromise()
      .then(response => response as IValueSetDictionary[])
      .catch(this.handleError);

to the following interface

export interface IValueSetDictionary {
  valueSet: {};
}

This maps a response from a 3rd party service which returns a JSON response similar to

{
  "<CONCENTRATE> | 6": "<CONCENTRATE>",
  "<PHYSICAL> | 5": "<PHYSICAL>",
  "NYMEX WARRANT IN MT | 12": "NYMEX WARRANT IN MT",
  "SHFE WARRANT | 13": "SHFE WARRANT"
}

I want some help with removing the '<' & '>' from the response.

Desired output

{
  "CONCENTRATE | 6": "CONCENTRATE",
  "PHYSICAL | 5": "PHYSICAL",
  "NYMEX WARRANT IN MT | 12": "NYMEX WARRANT IN MT",
  "SHFE WARRANT | 13": "SHFE WARRANT"
}

Basically, I want to get rid of the '<>' tags while mapping the response. I have not been able to figure out a neat way to do this in typescript.


Solution

  • One approach could be to stringify the object, remove the brackets with a given RegEx and parse the result again.

    Be aware: This could be a problem if the object could contain keys/values like

    'some < string which randomly contains opening and closing > brackets '

    function removeAngleBrackets(obj) {
        const jsonString = JSON.stringify(obj);
        const result= jsonString.replace(/<(.*?)>/g,'$1');
        return JSON.parse(result);
    }
    
    let o = {
      "<CONCENTRATE> | 6": "<CONCENTRATE>",
      "<PHYSICAL> | 5": "<PHYSICAL>",
      "NYMEX WARRANT IN MT | 12": "NYMEX WARRANT IN MT",
      "SHFE WARRANT | 13": "SHFE WARRANT"
    }
    
    console.log(removeAngleBrackets(o));