Angular 将对象转换为数组

标签 angular typescript

我有一个 json 对象,我尝试将其转换为数组,否则当我循环它时,我得到 [object object],在我的代码中我尝试了一些可行的方法,但它只显示每个字段的值而不是显示键 => 值。

如何在我的 html 中显示我的 json 的键和值? 有没有更好的方法将对象转换为数组?

json

{
  "toto": [
    "titi",
    "tata"
  ],
"foo": [
    "foobar",
    "footix"
  ]
}

ts.file

fetchPosts() {
    let resp = this.summaryService.getAllSummery()
      this.sub = resp.subscribe((res: Isummary[]) => {
        this.summaryArray = res
      });
  }

界面

export interface Isummary {
  toto:string[],
  foo:string[]
}

html

<div*ngFor="let post of summaryArray | keyvalue">
   <span>{{post.key}}</span>
   <span *ngfor="let value of post.value">{{ value }}</span>
</div>

最佳答案

您可以使用 KeyValuePipe而且您不必更改对象中的任何内容

export interface Isummary {
  toto: string[];
  foo: string[];
}

@Component({
  selector: "example",
  template: `
    <div *ngFor="let item of object | keyvalue">
      <span>key: {{ item.key }}</span>

      <span>Values</span>
      <span *ngFor="let value of item.value">{{ value }}</span>
    </div>
  `,
})
export class ExampleComponent {
  object: Isummary = {
    toto: ["titi", "tata"],
    foo: ["foobar", "footix"],
  };
}

或者您可以使用 Object.entries

@Component({
  selector: "example",
  template: `<div *ngFor="let item of object">
    <span>key: {{ item[0] }}</span>

    <span>Values</span>
    <span *ngFor="let value of item[1]">{{ value }}</span>
  </div>`,
})
export class ExampleComponent {
  object = Object.entries({
    toto: ["titi", "tata"],
    foo: ["foobar", "footix"],
  });
}

关于Angular 将对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68314022/

相关文章:

javascript - 开发新的 Angular 应用程序 - 为 Angular 2 做准备

Angular2 无法使用prototype.js

javascript - Angular 2 中的 Leaflet + Google - 瓷砖顺序错误

c# - 将 SharpKit 的 JsObject 转换为 TypeScript

c# - 在 vscode 中使用 Angular 4 调试 Asp.Net Core 应用程序

angular - 如何检查我的表单数组是否已经拥有该对象

c# - 如何使用Angular个人用户帐户身份验证自定义ASP.NET Core Web应用程序的登录页面?

javascript - Angular 4 Reactive Forms FormControl错误为空

javascript - .sort 在 Firefox 中不起作用,但在 chrome 中起作用

typescript - 是什么导致 Redux 中更新状态出现 "Delay"?