Gaining entry to a JSON object within an array

I've completed various courses on JSON and put in a lot of effort to troubleshoot this bug. However, it seems that my question is too specific and I require a practical example.

JSON

{
  "date": "2017-10-15",
  "league": "NHL",
  "odds": "spreads",
  "status": "200 OK",
  "updated": "2017-10-23 00:07 UTC",
  "games": [
    {
      "away": {
        "rot": "051",
        "odds": {
          "acesport": "-1.5 +178",
          "betphoenix": "-1.5 +177",
          "betus": "-1.5 +170",
          "bookmaker": "-1.5 +180",
          "bovada": "-1.5 +170",
          "dsi": "-1.5 +170",
          "easystreet": "-1.5 +180",
          "jazz": "-1.5 +175",
          "mirage": "-1.5 +180",
          "open": "-1.5 -110",
          "pinnacle": "-1.5 +192",
          "sbg": "-1.5 +175",
          "sia": "-1.5 +150",
          "sportsbet": "-1.5 +240",
          "station": "-1.5 +175",
          "westgate": "-1.5 +175"
        },
        "team": "Boston Bruins",
        "score": 1
      },
      "home": {
        "rot": "052",
        "odds": {
          "acesport": "+1.5 -208",
          "betphoenix": "+1.5 -217",
          "betus": "+1.5 -200",
          "bookmaker": "+1.5 -210",
          "bovada": "+1.5 -200",
          "dsi": "+1.5 -200",
          "easystreet": "+1.5 -210",
          "jazz": "+1.5 -205",
          "mirage": "+1.5 -220",
          "open": "+1.5 -110",
          "pinnacle": "+1.5 -214",
          "sbg": "+1.5 -210",
          "sia": "+1.5 -175",
          "sportsbet": "+1.5 -280",
          "station": "+1.5 -210",
          "westgate": "+1.5 -200"
        },
        "team": "Vegas Golden Knights",
        "score": 3
      },
      "time": "7:05 PM EST",
      "status": "Final"
    }
  ]
}

After researching and watching videos, I believe the code snippet below is close to the correct solution. The problem might be that this isn't just a value in an array, but another object?

for (i = 0; i <= body.games.length; i++){
    for (var key in body.games[i]) {
        console.log("Game " + (i +1));
        console.log(body.games[i][key].away.odds.acesport);
    }
}

Answer №1

It seems like you forgot to include a question in your post. For the sake of clarity, I will assume you are asking "How can I access an object within an array?" and "What could be the reason for my code not functioning as expected?"

Here is an example that may help illustrate the concept:

for (var i = 0; i < body.games.length; i++) {
    var game = body.games[i];
    console.log("Game number " + (i + 1));
    console.log(game.away.odds.acesport);
    for (var key in game) {
        // This loop will display the properties "away", "home", "time", and "status",
        // but it won't show the corresponding values like "object", "object",
        // "7:05 PM EST", and "Final".
        console.log("Game property: " + key);
    }
}

Answer №2

You are attempting to retrieve data from

body.games[i].away.away.odds.acesport
, but this method will not give you the desired result. Here are some alternative approaches that may be more effective:

Approach #1

Simplify by extracting values of known keys with the properties you need.

for (i = 0; i <= body.games.length - 1; i++){
  console.log("Game " + (i +1));
  console.log(body.games[i].away.odds.acesport);
  console.log(body.games[i].home.odds.acesport);
}

Approach #2

Check for the existence of properties like odds and acesport, making it more scalable.

for (i = 0; i <= body.games.length - 1; i++) {
  console.log("Game " + (i +1));
  for (var key in body.games[i]) {  
    var acesport = body.games[i][key].odds && body.games[i][key].odds.acesport;
    if (acesport) console.log(acesport);
  }
}

Approach #3

If you prefer cleaner code:

body.games.forEach(function(game, index) {
  console.log("Game " + index + 1);
  Object.keys(game).forEach(function (prop) {
    var acesport = game[prop].odds && game[prop].odds.acesport;
    if (acesport) console.log(acesport);
  });
});

For even cleaner code (using string templates and arrow functions):

body.games.forEach((game, index) => {
  console.log(`Game ${index + 1}`);
  Object.keys(game).forEach((prop) => {
    var acesport = game[prop].odds && game[prop].odds.acesport;
    if (acesport) console.log(acesport);
  });
});

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

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

Tips for incorporating JavaScript into elements that have been modified using jQuery's .html() method

Consider this example: $('#key').on('click', function(){ $('.task').html("<button id='key'>Button</button>"+Date()); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.j ...

Android is now asking for location permissions instead of Bluetooth permissions, which may vary depending on the version

I am currently troubleshooting a React Native application that relies heavily on Bluetooth permissions. However, I am encountering an issue with the Android platform where the Bluetooth permissions are appearing as unavailable. I have configured the permi ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

Prisma financial deal

I am attempting to upsert data and then iterate through an array to upsert values from another table. model ProductVariant { id Int @id @default(autoincrement()) name String @db.VarChar(50) photos ...

Out of the blue, my session stopped functioning

I am encountering a major issue with sessions. I am working on developing an application using "Redis" in node.js along with various libraries such as express. However, I have run into a problem where the sessions are no longer functioning properly. Desp ...

Exploring the power of Nestjs EventEmitter Module in combination with Serverless functions through the implementation of Async

I am working on implementing an asynchronous worker using a serverless lambda function with the assistance of the nestjs EventEmitter module. The handler is being triggered when an event is emitted, but the function closes before the async/await call. I ...

Implementing a feature to automatically set the datepicker value to the selected date upon page initialization

I am working with a datepicker element, identified by id="from_dt", and a button with id="fromToDate". When a date is selected from the datepicker and the button is clicked, the page will load. At that point, I want to transfer the selected date to a textb ...

Encountered an issue while attempting to assess Jackson deserialization for this specific

I am currently in the process of establishing a many-to-many relationship between movies and users. However, I encountered an error while attempting to save a movie: 2017-12-01 16:12:43.351 WARN 17328 --- [nio-8090-exec-5] .c.j.MappingJackson2HttpMessageC ...

Modifying the value of a variable causes a ripple effect on the value of another variable that had been linked to it

After running the code below, I am receiving values from MongoDB in the 'docs' variable: collection.find({"Stories._id":ObjectID(storyId)}, {"Stories.$":1}, function (e, docs) { var results = docs; results[0].Stories = []; } I ...

When comparing org.json.simple.JSONObject and org.json.JSONObject, the issue of JSONException not being able to be resolved as a

Could someone clarify the distinctions between org.json.simple.JSONObject and org.json.JSONObject? Also, I am encountering an issue with a code that uses org.json.JSONObject and org.json.JSONException. While editing the code in Eclipse (JUNO), it recogniz ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

Include JSON elements in the ajaxSubmit function

Here is a snippet of code I am working with: var o_titular = {id:'01',fecha:'2014-01-01'}; var o_dependientes = [ {id:'02',fecha:'2014-02-02'}, {id:'03',fecha:'2014-03-03'} ]; var o_fecha = &apo ...

Can you provide guidance on securing a REST API using Google authentication?

I'm currently working on developing a REST API using NodeJS and Passport for a single-page JavaScript application. I am struggling to find the right approach to securing my REST API with Google OAuth. Can someone guide me on how to achieve this? Any ...

Angular2: The NgFor directive is designed to work with Iterables like Arrays for data binding

I'm currently working on a university project to develop a web application consisting of a Web API and a Frontend that interacts with the API. The specific focus of this project is a recipe website. Although I have limited experience with technologies ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

Retrieve the quantity information from a JSON object

Hello everyone! I am new to programming and need help. How can I retrieve the 'qty' value of 0 using JSON and PHP from the following data: {"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]} I have attempted the following code: ...

Connect a function to create a new document element in order to modify the

I am attempting to intercept document.createElement in order to modify the value of the src property for each assignment. My current approach involves: var original = document.createElement; document.createElement = function (tag) { var element ...

Having trouble receiving a response from $.get method in localhost using jQuery

Attempting to send a GET request using jQuery in order to receive a dynamically determined namespace page. The index page (in Jade) contains a text input form that is being used by this script: script(src="http://code.jquery.com/jquery-1.11.1.js") script( ...