最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited Mar 15, 2022 at 22:19 Akber Iqbal 15k12 gold badges53 silver badges75 bronze badges asked Jul 8, 2019 at 12:52 MissarMissar 1171 gold badge1 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.ponent.html',
  styleUrls: ['./app.ponent.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);
  }
}

plete working stackblitz here

发布评论

评论列表(0)

  1. 暂无评论