Access Nested Object with Changing Wrapper

My problem is I want to access certain nested object but parent may change while doing JSON request.

  "ID": 752357,
  "name": "John Doe",
  "age": 25,
  "status": {},
  "detail": {
    "level": 12,
    "attack": "5",
    "def": "10",
  },
  "item": {
    "890099870": {
      "bag": {
        "12345": {
          "name": "Bones",
          "quantity": 338,
          "status": 0
        },
        "45678": {
          "name": "Iron Ores",
          "quantity": 99,
          "status": 0
        }
      },
      "expire": {
        "start": 1692288000,
        "end": 0,
      }
    }
  },

"item": {
** "890099870"**: {

This part keep changing depend on server update data. And item id will change base on what i have in my inventory.

I want to access and display name and quantity of all in inventory in html table like this.

| ID        | Name      | Quantity |
| --------  | --------  | -------- |
| 12345     | Bones     | 338      |
| 45678     | Iron Ores | 99       |

>Solution :

Use Object.values(product.item)[0] to access the value regardless its key:

const item = Object.entries(Object.values(product.item)[0].bag).map(([id, bag]) => ({id, ...bag}));
console.log(item);
<script>
const product = {
  "ID": 752357,
  "name": "John Doe",
  "age": 25,
  "status": {},
  "detail": {
    "level": 12,
    "attack": "5",
    "def": "10",
  },
  "item": {
    "890099870": {
      "bag": {
        "12345": {
          "name": "Bones",
          "quantity": 338,
          "status": 0
        },
        "45678": {
          "name": "Iron Ores",
          "quantity": 99,
          "status": 0
        }
      },
      "expire": {
        "start": 1692288000,
        "end": 0,
      }
    }
  },
}
</script>

Leave a Reply