Reuse Angular component 8 by changing the json structure

Asked

Viewed 120 times

0

I am with 2 similar json, however, with one more constant in one of them. I’d like to match the 2 so I can reuse the same component and on the same call.

Ex.:

"data": [
        {
            "id": 1,
            "titulo": "novaaaa",
            "thumbnail": null,
            "resumo": null,
            "autor": {
                "id": 1,
                "name": "teste"
            },
            "tags": [],
            ...
        }]

"data": [
        {
        "receitas": {
            {
                "id": 1,
                "titulo": "novaaaa",
                "thumbnail": null,
                "resumo": null,
                "autor": {
                    "id": 1,
                    "name": "teste"
                },
                "tags": [],
                ...

            }
          }] 

His call is like this today:

 this.service.getAll(type, id_type, '', this.page).subscribe(res => {

         this.content = res.data.data;
}... 

What is the best way and practice for me to match the 2 json and use it in this.content?

1 answer

1


I find it very strange that the return of the Api has different data structure, I think that this should not be so, but in your case it is possible to do what you want with a simple if/Else checking if the return has the property receitas or not through the Javascript method hasOwnProperty():

this.service.getAll(type, id_type, '', this.page).subscribe(res => {
   if(res.data.data[0].hasOwnProperty('receitas')) {
     this.content = res.data.data[0]['receitas'];      // content com receitas
   } else this.content = res.data.data[0];             // content sem receitas
}

OBS 1: When you say too constant, is actually a property the most.

OBS 2: Your second example of api return is wrong, has 2 keys - {{ one after the other, after recipes, and this characterizes a JSON with an invalid format.

OBS 3: I don’t know if you have access to Api, but try changing the property names, as you can see date. became redundant.

See an example of the result working here.

  • Hello, thank you so much for the reply. On remark 1 and 3, the return comes from the paginate standard of the Terminal that is doing the backend. On item 2, I actually just picked up an excerpt from the api return. So it seemed a little incomplete. In the example you did, is he considering the first position of the array, but using hasOwnProperty(), also meets in a loop? Thanks again.

  • Yes meets within a loop normally, such as a foreach() or map() for example.

  • I did it, thank you very much! Note: in the loop it looks like this: this.content.map( Function( elem ) { if(elem.hasOwnProperty('recipes')) { Return elem['recipes']; } Return elem; });

  • Good Rubens that’s right, success there!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.