簡體   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