【问题标题】:Angular-6: Convert string to array of a custom objectAngular-6:将字符串转换为自定义对象的数组
【发布时间】:2019-11-17 23:54:06
【问题描述】:

我已经生成了这个字符串

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

我想把它转换成一个对象数组来实现:

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

Expertise类是

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

您对解决这个问题有什么想法吗? 非常感谢。

【问题讨论】:

    标签: arrays json angular typescript angular6


    【解决方案1】:

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

    完成working stackblitz here

    【讨论】:

    • 您好@AkberIqbal 先生,非常感谢。它也有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2013-06-16
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多