Search code examples
javascriptarraysjsonjavascript-objects

Load nested object on an array dynamically with javascript


I have a json data in this format and I would like to load data in an array which is an object, without hard coding the object keys. I would like to get items and labels in each category and each category has it name for object key. At the moment I get the data by
...myData.labels.name; or ...items.name; which is not effective because the name changes depending on the category.

  [
  [
    {
      "key": "mykey",
      "category": "myCategoryKey",
      "category_label": "myCategoryLabel",
      "field": "filter",
      "items": {
        "name": [
          "item1",
          "item2"
        ]
      },
      "labels": {
        "name": [
          "Item1",
          "Item2"
        ]
      }
    },
    {
      "key": "mykey2",
      "category": "myCategoryKey2",
      "category_label": "myCategoryLabel2",
      "field": "filter",
      "items": {
        "name2": [
          "item1",
          "item2"
        ]
      },
      "labels": {
        "name3": [
          "Item1",
          "Item2"
        ]
      }
    }
  ]
]

Solution

  • Use Object.keys() to get Keys for items present if values change dynamically.

    And then use the keys to get corresponding values.

    var data = {
                "key": "mykey2",
                "category": "myCategoryKey2",
                "category_label": "myCategoryLabel2",
                "field": "filter",
                "items": {
                    "name2": [
                        "item1",
                        "item2"
                    ]
                },
                "labels": {
                    "name3": [
                        "Item1",
                        "Item2"
                    ]
     } }
     
     var labelsPresent = Object.keys(data.labels);
     
     console.log(labelsPresent);
     
     var labelValues= labelsPresent[0];
     console.log(data.labels[labelValues]);