简体   繁体   中英

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.

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.

It has little to do with typescript, it's the same thing in javascript as well. What you need to do is to transform the objects that you are getting in the desired form. Try something like this:

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

The cleanValueSet function is the one doing the actual replacement of the unwanted characters and also putting the object back together:

private cleanValueSet = (vs: IValueSetDictionary): IValueSetDictionary => {
  const result = Object.keys(vs.valueSet).reduce((acc, rawKey) => {
    const key = rawKey.replace(/[\<\>]/g, '');
    const value = (vs.valueSet[rawKey] as string).replace(/[\<\>]/g, '');
    acc[key] = value;
    return acc;
  }, {} as { [key: string]: string });

  return { valueSet: result };
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM