繁体   English   中英

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

[英]Angular-6: Convert string to array of a custom object

我有这个产生的字符串

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"}];

你有没有想过解决这个问题? 十分感谢。

你需要的是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);
  }
}

这里完成了stackblitz的工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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