Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

mapping - How to access object variable with spaces in it? Typescript

So I have an incoming object which looks like this:

Email: "[email protected]"
ID: "106150111352875619571"
Image URL: "https://lh3.googleusercontent.com/a-/AOh14Gi8zfXDXbMG_kvgmIs2yYiAGbuplyapc0gyjXqpTA=s96-c"
Name: "Edward Muldrew"
 

Which I try map to my object User

export class User {
    constructor(
        public ID: string,
        public Name: string,
        public Image_URL: string,
        public Email: string,
    ) { }
}
      

      var obj = localStorage.getItem('user') || '{}';
      this.user = JSON.parse(obj);

Everything maps fine except for the Image URL link as that variable has a space in it. This is in a typescript file and I am unsure of how to access it. I have tried using

obj['Image URL']

But this hasn't worked. Any other solutions?

question from:https://stackoverflow.com/questions/65887141/how-to-access-object-variable-with-spaces-in-it-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here you have:

const obj = {
  Email: "[email protected]",
  ID: "106150111352875619571",
  ['Image URL']: "https://lh3.googleusercontent.com/a-/AOh14Gi8zfXDXbMG_kvgmIs2yYiAGbuplyapc0gyjXqpTA=s96-c",
  Name: "Edward Muldrew",

}

type Obj = typeof obj

export class User implements Obj {
  public ID: string;
  public Name: string;
  public ['Image URL']: string;
  public Email: string;
  constructor(
    id: string,
    name: string,
    imageUrl: string,
    email: string,

  ) {
    this.ID = id;
    this.Name = name;
    this['Image URL'] = imageUrl;
    this.Email = email

  }
}

const foo = new User('1', 'John', 'http://example.com/data/index.png', '[email protected]')
var result = foo['Image URL'] // string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...