Access particular nested arrays within JSON objects that correspond to specific data using Javascript

Currently, I am utilizing an NBA API that allows me to search for players based on their last name. However, a common issue arises as multiple players can share the same last name.

An illustration of the response received from the API when sorting by last names is as follows:

   "players": [
    0: {
    "firstName":"Anthony"
    "lastName":"Davis"
    "teamId":"17"
    "yearsPro":"9"
    "collegeName":"Kentucky"
    "country":"USA"
    "playerId":"126"
    "dateOfBirth":"1993-03-11"
    "affiliation":"Kentucky/USA"
    "startNba":"2012"
    "heightInMeters":"2.08"
    "weightInKilograms":"114.8"
    
    1: {
    "firstName":"Deyonta"
    "lastName":"Davis"
    "teamId":"14"
    "yearsPro":"3"
    "collegeName":"Michigan State"
    "country":"USA"
    "playerId":"127"
    "dateOfBirth":"1996-12-02"
    "affiliation":"Michigan State/USA"
    "startNba":"2016"
    "heightInMeters":"2.11"
    "weightInKilograms":"107.5"
}

The results are extensive, necessitating my need to achieve two objectives:

Primarily, I aim to retrieve/filter the correct player using both their first and last names. In this extraction process, it remains imperative to retain the entire array of information associated with the matched player.

To simplify, I want to find 'Deyonta Davis', but upon discovery - I require all other relevant details pertaining to that player (such as years in the league, college attended, country of origin, etc.)

I have currently established a method to access the initial result of nested data within this API through the use of the last name inputted; however, the main predicament lies in the likelihood of the initial result not aligning with the desired player.

The objective is to integrate both first and last names in order to prevent inaccurate player pulls.

A snippet representing my current approach towards extracting information based on last name:

// Accessing API
    const splitmsg = message.content.split(' ')
    var lastnameurl = "https://api-nba-v1.p.rapidapi.com/players/lastName/" + splitmsg[1];
    axios.get(lastnameurl, {
      headers: {
      "x-rapidapi-key": apikey,
      "x-rapidapi-host": apihost
    }

// Deriving Player Information (initial result)
var playerfirstname = response.data.api.players[0].firstName;
var playerlastname = response.data.api.players[0].lastName;
var collegename = response.data.api.players[0].collegeName;
var countryname = response.data.api.players[0].country;
var playerDOB = response.data.api.players[0].dateOfBirth;
var yrspro = response.data.api.players[0].yearsPro;
var startednba = response.data.api.players[0].startNba;

Your assistance in resolving this matter would be greatly appreciated. Thank you.

Answer №1

Understanding the question correctly, the goal is to:

Find the first object in an array where the properties firstName and lastName match the desired values.

You can accomplish this by using the built-in find function.

const player = array.find(el => {
  return el.firstName === "Deyonta" && el.lastName === "Davis"
});

Just remember that if there is no such object in the array, the value of player will be undefined.

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

What is the best way to utilize WebSocket in Express.js and patiently await a response?

After configuring Node.js to run an HttpServer using Express.js, I found the need to integrate WebSocket (ws) to establish a connection with my device for data retrieval. My current implementation is as follows: import express from 'express'; im ...

Troubleshooting CSV Writing Problem in Python 2.7

I've encountered a strange issue with my Python code that interacts with Github's pull requests. When I print the parsed JSON output to the console, everything looks fine. However, when I try to output the same data to a CSV file, it gets cut off ...

Ensure to update the npm package version before making any Git commit

My project is built with Ember using NPM and I utilize Git for version control. I am looking for a way to update or bump the package.json version before or during a Git commit. Is there a method to accomplish this? Should I be implementing Git hooks? ...

Warning: Unhandled Promise Rejection - Alert: Unhandled Promise Rejection Detected - Attention: Deprecation Notice

Encountering the following error message: (node:18420) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined at C:\Users\ohrid\Desktop\backend2\routes\categories.js:27:24 at Layer.han ...

Combine two arrays and collapse one of the nested elements

I need help merging two arrays based on ID and flattening one of the objects. I haven't been able to find a solution for my specific case. This is what I'm attempting and what I've managed to achieve so far: const a = { someProperty: &a ...

Utilizing React portals for displaying a modal component upon clicking a table row

As I familiarize myself with React, the concept of portals in the developer documentation caught my attention. However, I am struggling to grasp how this portal component renders on-demand and how data can be passed to it to populate a modal. My current s ...

Modifying background image with Javascript

I've been working on developing a slideshow for one of the web pages I'm building. To achieve this, I set up a div with a unique class name that allows me to change the background image using JavaScript. Here's what I've accomplished so ...

Update the content within a document and implement jQuery to make it clickable

Within my webpage, there is a random occurrence of the word -FORM-. I am looking to replace this word with another text that includes dashes for creating a clickable div. Despite having some code that successfully replaces the text, it lacks the function ...

Decoding JSON data from OpenWeatherMap using Swift

Although I have successfully established the connection, I am encountering difficulty extracting the description from the weather Array. The issue lies in the fact that it is a Dictionary nested within an Array. {"weather": [{"id":801,& ...

The error remains a mystery to the console - could it be possibly linked to the onclick() method?

Despite checking thoroughly, the console remains empty. I came across this code in a video tutorial where it worked perfectly. Below is the simple code that I am currently using: function addItem() { inames = [] iqtyp = [] iprice = [] inames.pu ...

Guide on traversing and modifying properties within a intricate JSON structure using Node.js

Is there a way to update the value of "message" for "chatTemplateId":"5" and "mid":"b" to "Test2" in the JSON data below using node-js/javascript? In C# I would have used LINQ, but I'm not sure how to achieve this in an optimized manner in JavaScript/ ...

Dropdown menu not populating with options in AngularJS ngOptions

It's puzzling to me why the dropdown menu is not being populated by ng-options. Despite JSON data being returned from the service and successfully logged in the controller, ng-options seems to be failing at its task. <tr class="info"> <td ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

Connecting your Android app to a MongoDB database, specifically using MongoLab, involves a few key steps

I am a beginner with mongodb and now I am looking to integrate mongodb with my android application. Additionally, I am using mongolab for my database. On the mongolab website, I cannot find the "View JSON Objects" option that is shown in YouTube videos re ...

Exploring Next.js: Comparing data fetching in getInitialProps(): server-side versus client-side

Currently, I'm working with Next.js and have set up a custom server using Express. One of my pages needs to retrieve data from the database. When getInitialProps() is executed on the server side, it easily retrieves the necessary data from the databa ...

Validate time format using jQuery

In my current project, I have created an input field where users can enter a time in the format mm:hh. The default value of the input field is set to 09:00, but I want to implement client-side validation to ensure that the entered format is correct. Since ...

Access information from multiple div elements using JavaScript data-attributes

Having trouble retrieving data-attribute values from multiple divs with the same class when clicked. The goal is to display the data value of the clicked div. function playSound(e) { const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`) ...

"Troubleshooting the ineffectiveness of ng-disabled in AngularJS for multiple

When I disable a button for the status "created" in this scenario, it ends up disabling the same button for all rows. What I actually need is to only disable it for rows with the status "Created". <tbody> <tr ng-repeat="row in Reconcile ...

Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value. Below is the code for the directive: angular.module('app ...

Why am I receiving an empty object after making a post request?

Attempting to make a post request to another localhost server as I am using webpack in my project and unsure how to handle the default webpack server. Here is the code for my post request: btn_bag[0].addEventListener('click', (e) => { ...