Home > Mobile >  Transforming a complex object into an array
Transforming a complex object into an array

Time:12-18

I am creating a React app using data from an API. the response data is a long complicated object that looks something like this:

{
    "Frozen Products": [
        {
            "_id": "6181849285e8d8f86be2d9df",
            "name": "Peas (800g)",
            "category_id": "6181841060c425f76e57b603",
            "slug": "vegetables",
            "quantity": 16,
            "price": {
                "amount": 3.00
            },
            "thumbnail":"URI ...",,
            "images": [
                "URI ...",
            ],
            "synonyms": [
                "Veggies"
            ],
        },

//etc for many key/values inside this object ..
        
}

I need to access the information do display a category ("Frozen Products" in this case) and all the product names and images under it.

But I think I need to access each Key/Value pair by loopin through their index (example data[0]) not the Key name since they keys are dynamically created by an API. So how can I change this to:

{
   [ "Frozen Products": [
        {
            "_id": "6181849285e8d8f86be2d9df",
            "name": "Peas (800g)",
            "category_id": "6181841060c425f76e57b603",
            "slug": "vegetables",
            "quantity": 16,
            "price": {
                "amount": 3.00
            },
            "thumbnail":"URI ...",,
            "images": [
                "URI ...",
            ],
            "synonyms": [
                "Veggies"
            ],
        },
   ]

CodePudding user response:

I think you need something like this:

let data = {
    "Frozen Products": [
        {
            "_id": "6181849285e8d8f86be2d9df",
            ...
        }
    ],
    "Another Category": [...]    
}

let categories = Object.keys(data).map((key) => ({categoryName: key, products: data[key]}));

CodePudding user response:

you can loop through an object with for in iterator. No matter what key names are

for(key in object) {
  let value = object[key];
}
  • Related