0

I'm new to React-native and cannot figure out how to map this JSON:

{
    "Category Title": {
        "data": [
            {
                "id": 34,
                "name": "Blanditiis",
                "price": "10.30"
            },
            {
                "id": 25,
                "name": "Dolor omnis",
                "price": "10.37"
            }
        ]
    },
    "Second category": {
        "data": [
            {
                "id": 30,
                "name": "Cupiditate maiores consectetur ut quos",
                "price": "9.79"
            },
            {
                "id": 45,
                "name": "In facere sint quos",
                "price": "9.04"
            },
            {
                "id": 7,
                "name": "Necessitatibus",
                "price": "14.25",
            }
        ]
    },
    "Third category": {
        "data": [
            {
                "id": 39,
                "name": "Aliquam sed voluptates nihil dolore",
                "price": "5.66",
            }
        ]
    }
}

What I want is to map this as following:

<Text>{category_title}</Text> // foreach index of array
 {cards.map((the_date_from_the_json, index) => (
    <Card key={index} name={card.name} price={card.price} />
))}

The Card component is a working component. The only thing I can't figure out is how to map this multidimensional array; looping through easy data of the category with showing the Card an a Title of the Key of the Array.

1 Answer 1

1

You can use the object.entries and create an array

 const arr = new Array();
  for (const [key, value] of Object.entries(data)) {
    arr.push({ title: key, data: value.data });
  }

The data is the object above. Which will give the array like below

[{"title":"Category Title","data":[{"id":34,"name":"Blanditiis","price":"10.30"},{"id":25,"name":"Dolor omnis","price":"10.37"}]},{"title":"Second category","data":[{"id":30,"name":"Cupiditate maiores consectetur ut quos","price":"9.79"},{"id":45,"name":"In facere sint quos","price":"9.04"},{"id":7,"name":"Necessitatibus","price":"14.25"}]},{"title":"Third category","data":[{"id":39,"name":"Aliquam sed voluptates nihil dolore","price":"5.66"}]}]

You can map it like any other array now.

arr.map(item=>{
<Text>{item.title}</Text> 
 {item.data.map((card, index) => (
    <Card key={index} name={card.name} price={card.price} />
))}
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.