robert
robert

Reputation: 83

How to extract complex elements in a nested object in Javascript

A complex JSON is returned and I am trying to access the elements nested in the Object. Here is the JSON:

{
    "Meta Data": {
        "1. Information": "Daily Time Series with Splits and Dividend Events",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2021-02-12",
        "4. Output Size": "Full size",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2021-02-12": {
            "1. open": "243.9332",
            "2. high": "245.3",
            "3. low": "242.73",
            "4. close": "244.99",
            "5. adjusted close": "244.99",
            "6. volume": "16561079",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        },
        "2021-02-11": {
            "1. open": "244.78",
            "2. high": "245.15",
            "3. low": "242.15",
            "4. close": "244.49",
            "5. adjusted close": "244.49",
            "6. volume": "15751059",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        },
        "2021-02-10": {
            "1. open": "245.0",
            "2. high": "245.92",
            "3. low": "240.89",
            "4. close": "242.82",
            "5. adjusted close": "242.82",
            "6. volume": "22117240",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        },

I've seen all sorts of approaches using Object. but none are working for me. I think it's the fact that the keys are all unique to a date or the formatting is incorrect.

 const fetchData = async (e) => {
    fetch(requestUrl)
      .then(response => response.json())
      .then(data => {
        Object.keys(data['Time Series (Daily)']).forEach(key => {
          let value = data['Time Series (Daily)'][key]["5. adjusted close"];
          data_raw.push(value)
        });
        setData(data)
      })
      .catch(e => {
        setError("Fuckit")
      });
  };

I can access the object directly but can't seem to extract the data in to an array.

The direct call works but the array does not

    <>
      <h2>Ticker Data is: </h2>
      <ul>Quote: {mydata['Meta Data']['2. Symbol']}  </ul>
      <ul>Data Series: {mydata['Time Series (Daily)']["2021-02-12"]["5. adjusted close"]}</ul>
      <ul>All Data is: {close_data}</ul>
      <section>
        <h2>Error Data is: </h2>
        <p>{err}</p>

        <button onClick={fetchData}>
          Click it
            </button>


      </section>
    </>
  );

Upvotes: 1

Views: 266

Answers (2)

robert
robert

Reputation: 83

The following code worked for me.

const fetchData = () => {
    fetch(requestUrl)
      .then(response => response.json())
      .then(data => {
      
        Object.keys(data['Time Series (Daily)']).forEach((dateKey) => {
          last_close.push(data['Time Series (Daily)'][dateKey]['5. adjusted close'])
        })
       
        Object.keys(data['Meta Data']).forEach((metaKey) => {
          metadata.push(data['Meta Data'][metaKey])
        })
        setClosingData(last_close)
        setMetaData(metadata)

      })
      .catch(e => {
        setError("grr")
      });
  };

Upvotes: 1

Ajeet Shah
Ajeet Shah

Reputation: 19863

Your code is correct if you are looking for "close_data", you can run and check the below snippet output:

const data = {
    "Meta Data": {
        "1. Information": "Daily Time Series with Splits and Dividend Events",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2021-02-12",
        "4. Output Size": "Full size",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2021-02-12": {
            "1. open": "243.9332",
            "2. high": "245.3",
            "3. low": "242.73",
            "4. close": "244.99",
            "5. adjusted close": "244.99",
            "6. volume": "16561079",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        },
        "2021-02-11": {
            "1. open": "244.78",
            "2. high": "245.15",
            "3. low": "242.15",
            "4. close": "244.49",
            "5. adjusted close": "244.49",
            "6. volume": "15751059",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        },
        "2021-02-10": {
            "1. open": "245.0",
            "2. high": "245.92",
            "3. low": "240.89",
            "4. close": "242.82",
            "5. adjusted close": "242.82",
            "6. volume": "22117240",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        }
    }
}
const close_data = []

Object.keys(data['Time Series (Daily)']).forEach((dateKey) => {
  const value = data['Time Series (Daily)'][dateKey]
  close_data.push(value['5. adjusted close'])
})
console.log(close_data)

Upvotes: 1

Related Questions