user16356529
user16356529

Reputation:

Angular convert object to array

I have a json that an object I try to transform into an array otherwise when I loop on it I get [object object], in my code I tried something that works but it only shows me the values of each field instead of showing me key => value.

How to display the key and values of my json in my html ? is there a better way to convert an object to an array ?

json

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

ts.file

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

interface

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>

Upvotes: 3

Views: 6861

Answers (2)

Chris
Chris

Reputation: 2397

You can use the KeyValuePipe and you don't have to change anything in the object

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"],
  };
}

or you can use 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"],
  });
}

Upvotes: 2

Ling Vu
Ling Vu

Reputation: 5181

The answer of @Chris is the Angular way of doing it. Here is another approach from the js only side.

Assume we have:

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

You can use this, to transform it into an array:

const toArray = (data) => {
  return Object.keys(data).map(key => data[key]); 
} 

In the end it should look like this:

[
  [
    "titi",
    "tata"
  ],
  [
    "foobar",
    "footix"
  ]
]

Upvotes: 0

Related Questions