Search code examples
reactjsobjectreact-hookskey

unable to access dynamic object property and store to state in react


I'm trying to grab these arrays from one of the nasa open apis -> https://api.nasa.gov/neo/rest/v1/feed?start_date=START_DATE&end_date=END_DATE&api_key=API_KEY

I have a dynamic date in the params so the objects returned match the date, is there any way I can use my date (even though its a string) and turn it into a 'key' value so I can dynamically grab the objects I need?

like => "2021-08-26" would reference { 2021-08-26: [{},{},{}...] }

I have included my code so far with what I've tried, currently I'm trying to just select all the keys inside the {near_earth_objects} using forEach but I'm still getting an error data.near_earth_objects.forEach is not a function

constructor(){
        super();
        this.state={
            asteroids:[],
            time: []
            
        }
    }

    //grab the current time  (year-month-day) and store it in the state
    componentWillMount(){
        var today = new Date();
        var start = today.getFullYear()+'-'+0+(today.getMonth()+1)+'-'+today.getDate();  
        var end = today.getFullYear()+'-'+0+(today.getMonth()+1)+'-'+(today.getDate()+1); 

        this.setState({time: [start,end]})
    }


    componentDidMount(){
        
        fetch(`https://api.nasa.gov/neo/rest/v1/feed?start_date=${this.state.time[0]}&end_date=${this.state.time[1]}&api_key=ipAxYzaENbqRKb7GgzFPcH6QUBsHXY3QKB7uXOf5`
        )
      .then(response => response.json())
      .then((data) => {
            let asteroids = []
            data.near_earth_objects.forEach((arr)=>{
            asteroids.push(arr)
        })
        this.setState({asteroids:asteroids})
      });
    }
   

here is an example of the logged data I'm trying to access

enter image description here


Solution

  • It's important to note that the data is coming back as an object where the values are arrays. Since the return data is an object you cannot iterate over it.

    However, to get the data you can Object.values(object) (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) to get an array of the values. This will return something that looks like [ [...], [...] ]

    After that you can iterate over this information.

    In the end your code should look something like this:

    Object.values(data.near_earth_objects).forEach((arr)=>{
        asteroids.push(...arr)
    })