Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading