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

19,836

What you need is JSON.parse; it converts string to an object;

relevant 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);
  }
}

complete working stackblitz here

Share:
19,836
Missar
Author by

Missar

Updated on June 08, 2022

Comments

  • Missar
    Missar almost 2 years

    I have this produced string:

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

    I'd like to convert it to an array of Objects to have that:

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

    And Expertise class is

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

    I tried that:

    let array = str .replace('[{','').replace('}]','').split("},{").map(String);
    

    but that didn't resolve my problem, I got:

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

    instead of

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

    Have you please any idea about solving that ?. Big thanks.

  • Missar
    Missar almost 5 years
    Hello Sir @AkberIqbal, thanks a lot. It works as well.