Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing nested properties with dynamic property name

I have an object that is produced from this JSON:

{
    "data":  {
        "Meta Data": {
            "1. Information": "Monthly Prices (open, high, low, close) and Volumes",
            "2. Symbol": "MSFT",
            "3. Last Refreshed": "2017-08-18",
            "4. Time Zone": "US/Eastern"
        },
        "Monthly Time Series": {
            "2017-08-18": {
                "1. open": "73.1000",
                "2. high": "74.1000",
                "3. low": "71.2800",
                "4. close": "72.4900",
                "5. volume": "285933387"
            },
            "2017-07-31": {
                "1. open": "69.3300",
                "2. high": "74.4200",
                "3. low": "68.0200",
                "4. close": "72.7000",
                "5. volume": "451248934"
            }
        }
    }
}

Using Object.keys(), I was able to get the key "Monthly time series", but how can I access the keys within it? I want to run a for loop through the keys present in the "Monthly time series" key. How can I do that?

like image 627
Aayushi Avatar asked Sep 10 '25 11:09

Aayushi


1 Answers

You can use Object.keys() to get the array of keys, but instead of for...loop I suggest to iterate over the array of keys with Array.prototype.forEach().

Code:

const obj = {"data": {"Meta Data": {"1. Information": "Monthly Prices (open, high, low, close) and Volumes","2. Symbol": "MSFT","3. Last Refreshed": "2017-08-18","4. Time Zone": "US/Eastern"},"Monthly Time Series": {"2017-08-18": {"1. open": "73.1000","2. high": "74.1000","3. low": "71.2800","4. close": "72.4900","5. volume": "285933387"},"2017-07-31": {"1. open": "69.3300","2. high": "74.4200","3. low": "68.0200","4. close": "72.7000","5. volume": "451248934"}}}};

Object
  .keys(obj.data['Monthly Time Series'])
  .forEach(function (k) {
    console.log(obj.data['Monthly Time Series'][k]['1. open']);
  });
like image 105
Yosvel Quintero Arguelles Avatar answered Sep 13 '25 00:09

Yosvel Quintero Arguelles