0

How can I access array data inside my json object data?

    const [data, setData] = useState([])

    const getData = () => {
      axiosInstance
        .get(url + slug)
        .then(result => setData(result.data))
    }
    useEffect(() => {
      getData()
    }, [])        

Here are something I've tried:

  console.log(data['symbol'])
  console.log(data[0]['symbol'])
  console.log(data[0].symbol)

Here is the data being used in my state: enter image description here

To keep it simple, lets say I want to the access first array, and console log all values for symbol. How would I go about doing that?

7
  • console.log(data[0][0]). It will print first object inside first array of data. Commented Feb 15, 2021 at 22:38
  • I've tried that but I get Uncaught TypeError: Cannot read property '0' of undefined Commented Feb 15, 2021 at 22:39
  • Where are you logging it? If you have it outside the fetch, data is empty on the first render, so will throw an error. Also, you should either add getData to your useEffect dependency array, or move it inside. Commented Feb 15, 2021 at 22:41
  • It's outside the fetch, I'm just playing with my JSON object and getting a feel for it because I eventually will map this data. Commented Feb 15, 2021 at 22:45
  • 1
    Then check if it has been populated before trying to access it. if (data.length){console.log(...);} Commented Feb 15, 2021 at 22:47

2 Answers 2

1

Your object data looks like an array of arrays of objects.

This should work:

data[0][0].symbol

To log all the symbols of the first array:

console.log(data[0].map(item => item.symbol))
Sign up to request clarification or add additional context in comments.

1 Comment

From pilchard comment, I understand that if this is outside of the fetch then I will get an error. Not quite sure why because I can access the data through console log just fine.
1

To access the first array you can use this data[0] to map through all the objects inside the first array and log them you do the following

data[0].map(item => console.log(item.symbol))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.