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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With