Angular-6:将字符串转换为自定义对象数组

6

我有这个生成的字符串:

string str = [{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}]

我想将它转换为一个对象数组以获得以下内容:
listexps: Expertise[];
listexps = [{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}];

专业技能类是

export class Expertise
{
    id: number;
    name: string;
}

我试过了:
let array = str .replace('[{','').replace('}]','').split("},{").map(String);

但这并没有解决我的问题,我得到了:

"id":1,"name":"Angular","id":2,"name":"SpringBoot"

替代

[{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}];

你有没有任何解决这个问题的想法? 非常感谢。
1个回答

17

你需要的是JSON.parse; 它可以将字符串转换为对象;

相关的ts:

import { Component } from '@angular/core';
export class Expertise {
  id: number;
  name: string;
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  strIntoObj: Expertise[];

  constructor() {
    let str: string = '[{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}]';
    this.strIntoObj = JSON.parse(str);
    console.log(this.strIntoObj);
  }
}

完整的工作示例在此处。


1
您好,@AkberIqbal先生,非常感谢。它也能正常工作。 - Missar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接