Tips for accessing object data effectively in React Native

Hey, can someone help me out here? I'm struggling to figure out how to access the data in my object properly. For example, when I use console.log(response.data.Data), this is how my data looks:

Object {
  "2014": Object {
    "1": "3.385",
    "10": "-0.191",
    "11": "0.383",
    "12": "0.191",
    "2": "3.023",
    "3": "3.667",
    "4": "3.774",
    "5": "-2.045",
    "6": "2.088",
    "7": "5.455",
    "8": "-3.448",
    "9": "16.741",
  },
  "2015": Object {
    "1": "1.905",
    "10": "5.092",
    "11": "-4.070",
    "12": "7.475",
    "2": "5.421",
    "3": "5.142",
    "4": "-9.106",
    "5": "4.824",
    "6": "-4.425",
    "7": "-2.963",
    "8": "-1.527",
    "9": "-4.845",
  },
  "2016": Object {
    "1": "-1.504",
    "10": "-1.115",
    "11": "-7.891",
    "12": "8.392",
    "2": "2.863",
    "3": "-1.299",
    "4": "-1.880",
    "5": "-0.383",
    "6": "2.500",
    "7": "8.443",
    "8": "4.152",
    "9": "4.319",
  }
}

I'm having trouble accessing specific parts of the object using commands like console.log(response.data.Data.2014) or console.log(response.data.Data.object).

What's the best way for me to extract the year and month object data from this structure?

Thanks a lot!

Answer №1

You can achieve this in the following way

const info =  {
  "2017":  {
    "1": "2.385",
    "10": "-3.191",
    "11": "1.383",
    "12": "0.791",
    "2": "2.523",
    "3": "2.667",
    "4": "6.774",
    "5": "-1.045",
    "6": "1.088",
    "7": "3.455",
    "8": "-2.448",
    "9": "15.741",
  },
  "2018":  {
    "1": "2.905",
    "10": "4.092",
    "11": "-3.070",
    "12": "6.475",
    "2": "4.421",
    "3": "4.142",
    "4": "-8.106",
    "5": "3.824",
    "6": "-3.425",
    "7": "-1.963",
    "8": "-0.527",
    "9": "-3.845",
  },
  "2019":  {
    "1": "-0.504",
    "10": "-2.115",
    "11": "-6.891",
    "12": "7.392",
    "2": "1.863",
    "3": "-2.299",
    "4": "-0.880",
    "5": "-1.383",
    "6": "1.500",
    "7": "7.443",
    "8": "3.152",
    "9": "3.319",
  }
}



for (const period in info) {
  console.log(`${period}: ${info[period]}`);
  for (item month in info[period]) {
    console.log(`${month}: ${info[period][month]}`);
  }
}

Refer to this guide for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Answer №2

When examining your object, it appears that you are using an integer as the key. Even though you have converted the integer to a string, you still cannot access it with data.2014. Instead, you must use data["2014"].

✔ The key name in the data object will only function as data.key when the object is structured like this:

const data = {
   key: "Value"
}

or

const data = {
   key2022: "Value"
}

✘ However, if you include an integer at the beginning of the key or solely use an integer to name your key, you will need to utilize data["key"]:

const data = {
   "1key": "Value"
}

or

const data = {
   "1234": "Value"
}

✔ Therefore, in order to retrieve the value, you should follow this approach and opt for data["key"] instead of data.key for your object.

const data =  {
  "2014":  {
    "1": "3.385",
    "10": "-0.191",
    "11": "0.383",
    "12": "0.191",
    "2": "3.023",
    "3": "3.667",
    "4": "3.774",
    "5": "-2.045",
    "6": "2.088",
    "7": "5.455",
    "8": "-3.448",
    "9": "16.741",
  },
  "2015":  {
    "1": "1.905",
    "10": "5.092",
    "11": "-4.070",
    "12": "7.475",
    "2": "5.421",
    "3": "5.142",
    "4": "-9.106",
    "5": "4.824",
    "6": "-4.425",
    "7": "-2.963",
    "8": "-1.527",
    "9": "-4.845",
  },
  "2016":  {
    "1": "-1.504",
    "10": "-1.115",
    "11": "-7.891",
    "12": "8.392",
    "2": "2.863",
    "3": "-1.299",
    "4": "-1.880",
    "5": "-0.383",
    "6": "2.500",
    "7": "8.443",
    "8": "4.152",
    "9": "4.319",
  }
}



// To access the object of specific year use data["year"]
console.log(data["2014"])

// To access the value of specific month use data["year"]["month"]
console.log(data["2014"]["2"])

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

Outputting Javascript Strings via PHP

Currently, I am utilizing a web service that generates tables through JavaScript functions. However, I am in need of the table to be generated in plain HTML format instead. One potential solution to achieve this is by transferring the JavaScript string t ...

Is it possible for function in module.exports to access global variable within a module?

Suppose I have some code in a module: var foo = "bar"; module.exports = function() { console.log(foo); } And I try to access it from another module like this: var mod = require('above-module'); mod(); Will the second module be able to ac ...

Experiencing problems with integrating Slim framework and AngularJS, such as encountering a 404 error

Although this may seem like a repeat question, I am encountering an issue with using AngularJS with Slim Framework web services. I have set up a webservice to retrieve a student record with a URL structure like: http://www.slim.local/api/getstudent/1 ...

Stop fraudulent repetitive ajax calls to PHP

With my website, I've implemented a comment section for blog posts where users can share their thoughts. By clicking a button, an AJAX request is sent to PHP in JSON format. Upon receiving the data, PHP processes and validates it before inserting it i ...

Undefined result when performing an Ajax post

I'm attempting to use ajax to send the value of what is in the div's contents on a post. Specifically, I want to send the content of the div slick-active. In this example, console.log(data.results); would display 4 and 6. Below is the HTML code ...

Creating an Interactive Button in Vanilla JavaScript: Learn how to generate a button that appears only after a user has selected text, and utilize that selected text for a specific action

I am currently working on a project that involves allowing users to upload .docx files and read them directly within the app, alongside files uploaded by other users. To achieve this, I have extracted text from the docx files and displayed it in a separate ...

Is javascript or ajax the best choice for updating a database in asp.net mvc?

I need help with updating a row in my database based on a change event from a dropdown list. I am not sure whether to use javascript or ajax for this purpose as I want to avoid page refresh. Any recommendations on which method is best and where I can find ...

extract() of the incoming information

I'm currently tackling a project in Angular that involves user input into an input field. The task is to truncate the text at 27 characters and add "..." at the end if it exceeds that limit. I've attempted to achieve this using the slice() method ...

$set { "array.variable.value" :"newvalue"} utilize a different term besides "variable" or implement a new variable

When working with mongoose to store user data, one of the attributes is an array called items. In my additems.js file: const User = require('../models/User'); var array = user.items; array.indexOfObject = function (property, value) { ...

The function for fetching JSON data using AJAX is not functioning properly

Can someone help me troubleshoot why my code isn't working to retrieve a JSON file from a PHP page? Here is my PHP page: header('Content-type: application/json'); $jsonstart="{'files' : ["; $jsonend="]}"; $content="{'fir ...

What is the best way to create a loop for an array that holds objects?

Having an array with multiple objects raises a question. var profile = [ {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00", "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null}, {"MODE":"Eco" ...

The Vue and Element popover feature is unable to modify the current page

After hiding the popover and reopening it, it seems that the value of currentPage remains unchanged. Below is the HTML CODE: <el-popover placement="bottom" trigger="click" title="网段详情" @hide="popoverHide"> <el-table :data="in ...

A step-by-step guide on splitting an element into two separate elements using jquery

I have the following code snippet: <h4>user (role) on 26 Nov 2018 20:39:42 +00:00:</h4> My goal is to transform it into this structure: <h4>user (role)</h4> <p>on 26 Nov 2018 20:39:42 +00:00:</p> The <h4> eleme ...

Can you show me the method to retrieve the value of client.query in Node JS using PG?

I have been working with node.js to establish a database connection with postgresql. Here is what my dbConfig.js file looks like: var pg = require('pg'); var client = new pg.Client({ host:'myhoost', port:'5432', ...

When searching for a newly created element, getElementById consistently returns null

I need to create a duplicate element and assign it a new ID and name so that I can find it later. Here is an example: <div id="contDiv"> <div style="float:left"> filename </div> <div style="margin-left: 323px"> playtime(in Sek.) &l ...

Setting the borderRadius for a web view on Android Maps V3: A complete guide

In my application, I am using Android Map V3 and have encountered a bug specific to the Kit-Kat version. The chromium kit throws up an error message - nativeOnDraw failed; clearing to background color, which prevents the map from being displayed. Despite ...

Ways to retrieve items from an array based on their area_id

I need assistance with extracting customers from an array based on their area_id. For example, if I provide area_id 7, I should get a new array containing all the customers with area_id 7. "customers": [ { "id&q ...

Obtaining an array of objects through the reduction of another array

Currently, my goal is to extract an array of objects from another array. Let's say I have an array consisting of strings: const strArr = ["Some", "Thing"]; The task at hand is to create a new Array containing 2 objects for each st ...

Uploading Images to Cloudinary in a MERN Stack: A Step-by-Step Guide

I am facing an issue while trying to store company details, including a company logo, in Mongo DB. I am attempting to upload the image to Cloudinary and then save the URL in Mongo DB along with other details. Currently, my code is not functioning as expec ...

Exploring the concept of Variable Scope within a jQuery promise

Picture yourself executing the following code snippet within a JavaScript function named Fetch. function Fetch(context) { var request = $.ajax({...}); request.done(function(response) { // It appears that context is accessible here and in scope. ...