Javascript JSON array returns an empty set

I am facing an issue with my code where the keys are not always consistently named.

When I try to use key numbers instead, the code stops working.

Here is the object I am dealing with:

{
  "timestamp": 1622844000,
  "datetime": "2021-06-05 00:00:00",
  "COMBINED COUNT": [ -3, 0, 3, -109 ]
}

This is the code I have written to read the data and populate a Google chart:

success: function(obj) {
  for (var i = 0; i < obj.length; i++) {                        
    var temp = [JSON.stringify(obj[i]["datetime"]).substr(11,6) , Number(JSON.stringify(obj[i]["COMBINED COUNT"][0])) , "blue"];
    chartdata.push(temp);
  }

The output looks like this:

00:00,-3,blue,

However, when I try to change 'datetime' to 1 and 'COMBINED COUNT' to 2, the code doesn't produce any result.

success: function(obj) {
  for (var i = 0; i < obj.length; i++) {                        
    var temp = [JSON.stringify(obj[i][1]).substr(11,6) , Number(JSON.stringify(obj[i][2][0])) , "blue"];
    chartdata.push(temp);
  }

Can anyone explain why this happens? And what should I do in order to access the correct key values?

Thank you in advance!

Answer №1

The problem arises from the method of accessing an object's property. Based on the information provided, it appears that you are dealing with an array of objects.

When using obj[i][1], you are attempting to access a property with the key 1 in the object at index i. However, this property is not present in the object. On the other hand, if you access it as obj[i]["datetime"], you will get the desired result since the property datetime exists. The same logic applies to COMBINED COUNT.

Answer №2

After an extensive search, I finally discovered the solution:

Since the first and second keys in my object always hold the key values I need, I came up with this approach:

var key1 = Object.keys(obj[0])[1];
var key2 = Object.keys(obj[0])[2];
var temp = [JSON.stringify(obj[0][key1]).substr(11,6) , Number(JSON.stringify(obj[0][key2][0])) , "blue"];

Key1 retrieves the name of the 1st key in the object.

Key2 fetches the name of the 2nd key in the object.

I then use these key names within the 'temp' section to obtain the desired output. This method allows me to manipulate any key names and retrieve the necessary information.

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

Guide to dynamically rendering VueJS templates within a custom element

Currently, my Vue application relies on Esri's Mapping API for functionality. One feature provided by the Esri API allows me to define a popup template content using an object: const popupWindowTemplate = { title: "{mag} magnitude near {place}", ...

The mysterious case of the vanishing close button on Curator.io's mobile

Currently, I am using curator.io aggregator to showcase my Instagram feed on the website. An issue arises when switching to mobile view as the close button (class="crt-close") disappears. You can see an example of this here: To replicate the pr ...

Enclosing data types in Typescript

There is a factory method in my codebase that performs computations and manipulations. Additionally, there is a generic method called doSomething. I am looking for a way to avoid specifying the type for doSomething every time it's called. Instead, I w ...

What is the best way to add an event listener to every item in a list within a Vue component

Here is a component structure that I am working with: Vue.component('navbar', { props: ['navitem'], methods: { users: function () { //users code }, test:function(){ } }, template: '<li v-on:cl ...

How is it possible for a function to accept (int *&) as an argument?

Here is a function that splits an array into two separate arrays. The first output array will contain the elements from the input array between the specified indices, while the second output array will contain the remaining entries. void splitArray(int *a ...

Exploring JSON data and retrieving information from a Dictionary

{ ac = 0; storeLocation = "<null>"; storeSizeSqFt = 1000; tinNumber = testdummy4y58; wirelessInternet = 0; } In the response above, a code has been included: func StoreInfo(notification : NSNotification){ if let result = notificat ...

Angular ng-show does not seem to evaluate properly

After receiving the JSON array object below: "Tools": [ { "name": "Submit a Claim", "position": 1, "isOn": true, "alert": null }, { "name": "My Recurring Claims", "position": 2, "isOn": true, "alert": null }, { "name": "Online Enrollment ...

How can I display a specific element from a child Component when the main Component is clicked on in React?

I am currently working on my first React project and facing a challenge. I have a dropdown list on my main homepage that displays specific details when clicked. However, I am struggling to show the right corresponding detail (for example, black&white paren ...

Updating the JSON data with a new row

I am trying to dynamically add a new row to my JSON data when the user clicks on a link. Despite not receiving any errors, I am unable to see the updated JSON in my alert message. $(document).ready( function(){ people = { "COLUMNS":["NAME","AGE"], ...

Differences between class and prototype Array.isArray

Throughout my coding journey, I've often heard the saying "Classes are just syntactic sugar for prototypes." However, an interesting example challenges this notion. function SubArray() {} SubArray.prototype = new Array( ); console.log(Array.isArray( ...

Issue with Bower not adhering to bower.json specifications during installation

https://i.sstatic.net/tJocZ.png Everything you need to know is in the image - I am attempting to install a specific version of angular-bootstrap. When I execute: bower install angular-bootstrap#0.13.0 --save it asks for my resolution answer, even though ...

Handling invalid JSON strings in controller functions with JavaScript and Node.js

Issue with Incorrect JSON Formatting in Node.js Controller Function Upon sending a JSON object via AJAX to a route in Node.js, the req.body data received in the controller function seems to be incorrectly formatted. What could be causing this issue? Java ...

Utilizing TailwindCSS animations for dynamically displayed components in React

Is there a way to animate the transition of a component between its open and closed states in React using TailwindCSS when conditionally rendering based on state? {successMessage && ( <div className="flex transition-all ease-i ...

Finding the second through eighth elements in a protractor using a CSS locator

Recently, I have been experimenting with protractor and facing a limitation when trying to reference elements. The only way to refer to them is through CSS, as they only have a class attribute provided. The issue arises when there are more than 7 elements ...

When on a touch screen, event.relatedTarget will be null during a focusout event

When working with a textarea, I am trying to use the focusout event to capture the value of the clicked button that triggered the focusout, so I can later click it after some processing. This solution is effective on most devices, but I am encountering iss ...

Retrieve the data attribute associated with the chosen dropdown selections

I'm currently facing an issue with assigning a custom data attribute to a select box option and then transferring that value to a hidden form field. Here is the HTML I am working with: <select id="sampleorder" multiple="multiple"> <option ...

Send a parameter to be used as a link attribute in a pop-up box

I am seeking a way to pass a URL for my modal that relies on extracting the adder variable from the main HTML document. While I understand how to pass variables as text (using spans) to a modal, I am unsure how to incorporate a variable in an anchor <a ...

Optimizing the .includes() method for array searching with objects

In my current project, I am managing a large hardcoded array of objects that act as a database. These objects contain properties like title and content. One of the challenges I am facing involves enhancing the existing search functionality to return all ob ...

What is the process for sending a message from the internet to a mobile device?

We are currently in the process of developing a website that sends SMS alerts to users for specific services, however I am struggling to set up a script that can perform this function. If anyone has any suggestions or recommendations for a solution, pleas ...

Steps for recognizing XML nodes that translate to an Array when converted to JSON

When it comes to converting XML to a JSON string, I am looking to pinpoint which nodes in the XML markup can be considered arrays in JSON format, indicated by the "[" symbol. My approach is to identify nodes that close and then immediately reopen, similar ...