[Fixed] How to show Contents.Category array in object using .then

Issue

I get this JSON

[
        {
            "Id": "15",
            "Category": "Our Values,WIDE",
        },
        {
            "Id": "19",
            "Category": "Art,History,Culture",
        },
        {
            "Id": "20",
            "Category": "Our Values,WIDE",
        },{.......}
    ]

from this.CrewDataContents below:

LoadData() {
    this.dataService.GetData(0, 3).then(models => {
        this.CrewData = models;
        this.CrewDataContents = models.reduce((r, { Contents }) => {
            Contents.forEach(o => r.push({ ...o }));
            return r;
        }, []);
        console.log(this.CrewDataContents );
    });
}

From this.CrewDataContents I want to get only Category.

Can you share with me any idea please? How to get Category from function below? I tried to use .filter and .find but nothing happens.

Solution

I think thats it:

const jsonData = [
        {
            "Id": "15",
            "Category": "Our Values,WIDE",
        },
        {
            "Id": "19",
            "Category": "Art,History,Culture",
        },
        {
            "Id": "20",
            "Category": "Our Values,WIDE",
        }
    ]
var categoryData:String[] = [];
jsonData.forEach(element => {
    categoryData.push(element.Category);
})
console.log(categoryData);

Output:

["Our Values,WIDE", "Art,History,Culture", "Our Values,WIDE"]

So all you have to do, inside you .then function, you get the array, in my example the array you get from your backend is jsonData. Iterate over it, access the Category field and push that into a new array.

Leave a Reply

(*) Required, Your email will not be published