Retrieving and displaying complex JSON object structures

I'm encountering a challenge when trying to access nested keys within an object. Specifically, I am attempting to display the "kilometers_per_second" values found in the "relative_velocity" section under "close_approach_data".

Despite my efforts, I keep running into errors and can't seem to pinpoint where I'm going wrong. Any assistance would be greatly appreciated.

const asteroidData = near_earth_objects
        .map((data) => data.close_approach_data[0])
        .map((e) => e.relative_velocity); 

// TypeError: Cannot read property 'relative_velocity' of undefined

or

const asteroidData = near_earth_objects
          .map((data) => data.close_approach_data[0].relative_velocity);

// TypeError: Cannot read property 'relative_velocity' of undefined

Here is the JSON object structure:

 "near_earth_objects": [
        {
            "links": {
                "self": "http://www.neowsapp.com/rest/v1/neo/2021277?api_key=24TE7EgNfmXIvdb6vNNZGBWx8s54XbZzCCi2oAdN"
            },
            "id": "2021277",
            "neo_reference_id": "2021277",
            "name": "21277 (1996 TO5)",
            "designation": "21277",
            "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2021277",
            "absolute_magnitude_h": 16.1,
            "estimated_diameter": {
                "kilometers": {
                    "estimated_diameter_min": 1.6016033798,
                    "estimated_diameter_max": 3.5812940302
                },
                "meters": {
                    "estimated_diameter_min": 1601.6033797856,
                    "estimated_diameter_max": 3581.2940301941
                },
                "miles": {
                    "estimated_diameter_min": 0.9951898937,
                    "estimated_diameter_max": 2.2253122528
                },
                "feet": {
                    "estimated_diameter_min": 5254.6044325359,
                    "estimated_diameter_max": 11749.652706022
                }
            },
            "is_potentially_hazardous_asteroid": false,
            "close_approach_data": [
                {
                    "close_approach_date": "1945-06-07",
                    "close_approach_date_full": "1945-Jun-07 22:35",
                    "epoch_date_close_approach": -775272300000,
                    "relative_velocity": {
                        "kilometers_per_second": "15.5094751879",
                        "kilometers_per_hour": "55834.1106763388",
                        "miles_per_hour": "34693.1450477507"
                    },
                    "miss_distance": {
                        "astronomical": "0.0334232973",
                        "lunar": "13.0016626497",
                        "kilometers": "5000054.084456751",
                        "miles": "3106889.5396991238"
                    },
                    "orbiting_body": "Mars"
                }
            ],
            "is_sentry_object": false
        },

       // Object continues repeating the above structure

Answer №1

Are you looking for the specific kilometers_per_second values only?

let celestial_objects =  [
        {
            "links": {
                "self": "http://www.cosmosapp.com/rest/v1/celestial/2021277?api_key=24TE7EgNfmXIvdb6vNNZGBWx8s54XbZzCCi2oAdN"
            },
            "id": "2021277",
            "neo_reference_id": "2021277",
            "name": "21277 (1996 TO5)",
            "designation": "21277",
            "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2021277",
            "absolute_magnitude_h": 16.1,
            "estimated_diameter": {
                "kilometers": {
                    "estimated_diameter_min": 1.6016033798,
                    "estimated_diameter_max": 3.5812940302
                },
                "meters": {
                    "estimated_diameter_min": 1601.6033797856,
                    "estimated_diameter_max": 3581.2940301941
                },
                "miles": {
                    "estimated_diameter_min": 0.9951898937,
                    "estimated_diameter_max": 2.2253122528
                },
                "feet": {
                    "estimated_diameter_min": 5254.6044325359,
                    "estimated_diameter_max": 11749.652706022
                }
            },
            "is_potentially_hazardous_asteroid": false,
            "close_approach_data": [
                {
                    "close_approach_date": "1945-06-07",
                    "close_approach_date_full": "1945-Jun-07 22:35",
                    "epoch_date_close_approach": -775272300000,
                    "relative_velocity": {
                        "kilometers_per_second": "15.5094751879",
                        "kilometers_per_hour": "55834.1106763388",
                        "miles_per_hour": "34693.1450477507"
                    },
                    "miss_distance": {
                        "astronomical": "0.0334232973",
                        "lunar": "13.0016626497",
                        "kilometers": "5000054.084456751",
                        "miles": "3106889.5396991238"
                    },
                    "orbiting_body": "Mars"
                }
            ],
            "is_sentry_object": false
        }];

let output = celestial_objects.flatMap(({close_approach_data }) => close_approach_data.map(({relative_velocity})=> relative_velocity.kilometers_per_second));

console.log(output);

Answer №2

your code is correct, you just need to convert the raw json data for "near_earth_objects"

for example

const near_earth_objects = JSON.parse(JSON.stringify('YOUR_NEAR_EARTH')).near_earth_objects; 
const asteroidData = near_earth_objects
         .map((data) => data.close_approach_data[0].relative_velocity);

here is an updated version

const near_earth_objects_json = 
{ "near_earth_objects" : [
        {
            "links": {
                "self": "http://www.neowsapp.com/rest/v1/neo/2021277?api_key=24TE7EgNfmXIvdb6vNNZGBWx8s54XbZzCCi2oAdN"
            },
            "id": "2021277",
            "neo_reference_id": "2021277",
            "name": "21277 (1996 TO5)",
            "designation": "21277",
            "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2021277",
            "absolute_magnitude_h": 16.1,
            "estimated_diameter": {
                "kilometers": {
                    "estimated_diameter_min": 1.6016033798,
                    "estimated_diameter_max": 3.5812940302
                },
                "meters": {
                    "estimated_diameter_min": 1601.6033797856,
                    "estimated_diameter_max": 3581.2940301941
                },
                "miles": {
                    "estimated_diameter_min": 0.9951898937,
                    "estimated_diameter_max": 2.2253122528
                },
                "feet": {
                    "estimated_diameter_min": 5254.6044325359,
                    "estimated_diameter_max": 11749.652706022
                }
            },
            "is_potentially_hazardous_asteroid": false,
            "close_approach_data": [
                {
                    "close_approach_date": "1945-06-07",
                    "close_approach_date_full": "1945-Jun-07 22:35",
                    "epoch_date_close_approach": -775272300000,
                    "relative_velocity": {
                        "kilometers_per_second": "15.5094751879",
                        "kilometers_per_hour": "55834.1106763388",
                        "miles_per_hour": "34693.1450477507"
                    },
                    "miss_distance": {
                        "astronomical": "0.0334232973",
                        "lunar": "13.0016626497",
                        "kilometers": "5000054.084456751",
                        "miles": "3106889.5396991238"
                    },
                    "orbiting_body": "Mars"
                }
            ],
            "is_sentry_object": false
        },
        {
            "links": {
                "self": "http://www.neowsapp.com/rest/v1/neo/2021277?api_key=24TE7EgNfmXIvdb6vNNZGBWx8s54XbZzCCi2oAdN"
            },
            "id": "2021277",
            "neo_reference_id": "2021277",
            "name": "21277 (1996 TO5)",
            "designation": "21277",
            "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2021277",
            "absolute_magnitude_h": 16.1,
            "estimated_diameter": {
                "kilometers": {
                    "estimated_diameter_min": 1.6016033798,
                    "estimated_diameter_max": 3.5812940302
                },
                "meters": {
                    "estimated_diameter_min": 1601.6033797856,
                    "estimated_diameter_max": 3581.2940301941
                },
                "miles": {
                    "estimated_diameter_min": 0.9951898937,
                    "estimated_diameter_max": 2.2253122528
                },
                "feet": {
                    "estimated_diameter_min": 5254.6044325359,
                    "estimated_diameter_max": 11749.652706022
                }
            },
            "is_potentially_hazardous_asteroid": false,
            "close_approach_data": [
                {
                    "close_approach_date": "1945-06-07",
                    "close_approach_date_full": "1945-Jun-07 22:35",
                    "epoch_date_close_approach": -775272300000,
                    "relative_velocity": {
                        "kilometers_per_second": "15.5094751879",
                        "kilometers_per_hour": "55834.1106763388",
                        "miles_per_hour": "34693.1450477507"
                    },
                    "miss_distance": {
                        "astronomical": "0.0334232973",
                        "lunar": "13.0016626497",
                        "kilometers": "5000054.084456751",
                        "miles": "3106889.5396991238"
                    },
                    "orbiting_body": "Mars"
                }
            ],
            "is_sentry_object": false
        } ]
   }     


const near_earth_objects = JSON.parse(JSON.stringify(near_earth_objects_json)).near_earth_objects;

const asteroidData = near_earth_objects
         .map((data) => data.close_approach_data[0].relative_velocity);
        console.log(asteroidData);

If you only need kilometers_per_second, you can use this approach

const asteroidData = near_earth_objects
          .map((data) => data.close_approach_data[0].relative_velocity.kilometers_per_second);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with Vue.js array filtering feature in my program

My Vue.js code includes a search input with a dropdown menu populated by an API data array called categories. I am attempting to implement a filter on the search input so that when a value is typed, it filters the dropdown menu items based on the API data. ...

Retrieve a targeted data value from a JSON object based on an array value

Looking at the JSON array and another array provided below. JSON OBJECT { id: 1, name: 'abc', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbebdbc9fb8b2beb6b3f1bcb0b2">[emai ...

When trying to access the ShadowRoot in Firefox using Selenium, an error is thrown: JavaScriptException - Cyclic object

I'm currently working on automating the Space Invaders game on www.freeinvaders.org using Python and Selenium. The game itself is operated through an HTML5 canvas element enclosed within a shadow-root. Referencing a solution provided in this thread, ...

What is the total number of webgl.draw calls generated by Three.js when rendering a specific quantity of geometries, materials, and meshes?

Can you help me determine the total drawArrays/drawElements calls required by THREE.renderer.render(scene, camera)? I speculate one call per geometry, incorporating attributes for materials/mesh properties. Is my assumption accurate or am I overlooking ce ...

Difficulty in rendering all facets of a 3D object with Three.js and Fresnel Shader

I am delving into the world of Three.js and JavaScript coding for the first time. Lately, I have been experimenting with Shaders and Shader Materials. The issue I encountered was when I loaded a mesh with a Fresnel material. While the surface material app ...

Enhancing jQuery's ScrollTop Functionality

My jQuery script for scrolling to the top of a container seems to accelerate after it starts. It begins slowly and then speeds up. Is there a way to prevent this lag at the beginning and maintain a consistent speed throughout the entire scroll? // Once t ...

Fixing <Empty JSON content> error in WSO2 EI: A step-by-step guide to

An API is set up with an InSequence that retrieves a JSON file from the registry and puts it in OutSequence to respond to the caller. Various settings were adjusted to fix the issue, such as changing literals, paths to reach resources, and property mediat ...

Disabling a button based on the state of a switch button using React and Material UI

For the task at hand, we need to ensure that the button is only activated when the switch button's state changes. This state is received as a prop and needs to be validated correctly within the handleChangeState function. const CustomSwitch = ({name, ...

I require integrating another element alongside this button

I am trying to create a button component that, when clicked, will display another component along with it. However, I am unsure of how to achieve this. Take a look at the plantioComp return - this is the component that I want the button to trigger. <t ...

What is the most efficient way to condense multiple repetitive case statements?

Within my code, I have multiple case statements that are quite similar, with the only difference being the argument 'key' from the function click(key). The variable 'c' is represented as JSON. The challenge lies in incorporating the ar ...

How to close an iframe with javascript or jquery?

I am working with a series of iframes on my website. I am trying to figure out how to close the last iframe in the list when a button is clicked. Can someone please provide guidance on how to achieve this? Specifically, I am looking to execute a window.cl ...

JavaScript - Error encountered when accessing information from elements in the DOM

Just started learning javascript and encountering a problem that I can't seem to solve. I'm attempting to assign the className of a <div> element to a variable, but I keep receiving this error message: scripts.js:30 Uncaught TypeError: Can ...

Activate a Python Selenium function to click on a datepicker element

Looking for some help with selenium as I navigate my way around passing values into a form. While I've managed to successfully input values into regular text boxes, I'm struggling with the onclick datepicker function. Here's what I have so f ...

Utilizing the <Link> component in React Router to generate URLs based on the root domain

When users visit goodsite.com, they encounter a link created using react router. The link code snippet is as follows: <TableCell component={Link} to={`happy/${thing.id}`} > {thing.name} </TableCell> This particular link is situa ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

Steps to set up Feathers instance in Jest environment once

When running Jest tests, I want to utilize only one instance of feathers "app" throughout. This is how I currently import app in each test: const app = require('../../src/app'); describe(`service`, () => { it('registered the service&ap ...

Using Sequelize to update all values in a JSON file through an Express router.put operation

I've been working on a feature in my Express router that updates data in a MySQL schema for 'members' of clubs. The members table has various columns like member_id, forename, surname, address, etc. I've successfully created an Express ...

Discovering when the DOM has finished rendering in AngularJS with ng-repeat

I am looking for a way to trigger an alert or message upon completion of rendering in my HTML DOM using AngularJS, specifically when dealing with multiple ng-repeats. HTML Code: <body> <div ng-controller="Ctrl"> <div ng-repeat= ...

What is the best way to delete a CSS class from a specific element in a list using React?

I need to implement a functionality in React that removes a specific CSS class from an item when clicking on that item's button, triggering the appearance of a menu. Here is my code snippet. import "./Homepage.css" import React, { useState, ...

Error: Angular - encountering undefined response when making HTTP request

When making a HTTP GET request to my backend, it returns the following JSON data: "{\"instID\":\"2018#10#30\",\"procID\":1161006,\"threadNum\":0,\"status\":2}", "{\"instID\":\"2018#1 ...