Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 929
Missar Avatar asked Jul 08 '19 12:07

Missar


1 Answers

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

like image 141
Akber Iqbal Avatar answered Oct 21 '22 19:10

Akber Iqbal