6

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.

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.