When accessing a sub-array directly within an object, it transforms into a collection of nested objects

Is there a way to pass an array of objects to canvasJS? I am trying to include this array as part of a more complex object that is passed from PHP to a JS script. Here is my current approach:

var active_alarms_data = JSON.parse('<?php echo json_encode($activePriceAlarms,JSON_NUMERIC_CHECK);?>');

I also attempted:

var active_alarms_data = <?php echo json_encode($activePriceAlarms,JSON_NUMERIC_CHECK);?>;

Here is the structure of the main object:

https://i.sstatic.net/27cNq.png

The chart data can be found in the sub-array factory_made_avg_graph_prices_stats. While printing the entire object to the console, it seems that this field is correctly formatted as an array with 104 elements indexed from 0 to 103. This is what I need! However, when I try to access the array directly, I encounter something unexpected:

console.log("ELEMENT 0: " + active_alarms_data[i].graph.factory_made_avg_graph_prices_stats);

The output is different and the chart remains empty. It appears that the expected data format may not match the previous one. Any suggestions on how to resolve this issue?

Answer №1

Your code is perfectly fine.

Don't let the console log confuse you. The current method of accessing each element will work without any issues. The reason for seeing [object Object] is due to JavaScript attempting to convert non-strings to strings when using the '+' operator for concatenation.

You are simply viewing a string representation of each object in the array. To see just the array without "ELEMENT 0:", remove that part from the console log as shown below:

const obj = { test: [{ foo: 'bar' }] }
console.log('ELEMENT 0: ' + obj.test)
console.log(obj.test)

Alternatively, if you prefer to keep "Element 0" in the log, use a comma instead of direct concatenation like this:

const obj = { test: [{ foo: 'bar' }] }
console.log('ELEMENT 0:', obj.test)

Answer №2

Here is an example of a console output:

console.log("ELEMENT 0: " , 
active_alarms_data[i].graph.factory_made_avg_graph_prices_stats);

In the console, change the '+' to ','

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

Error: You can't call .text as a function in jQuery

While trying to retrieve the text from my td, I encountered the following error: $tds[2].text is not a function. The output of console.log('td',$tds[2]) shows: https://i.stack.imgur.com/OUngP.png $(document).ready(function() { $trs = $(&ap ...

Assistance with JavaScript regular expressions for dividing a string into days, hours, and minutes (accounting for plural or singular forms)

My challenge is with handling different variations in a string var str = "2 Days, 2 Hours 10 Minutes"; When I use : str.split(/Days/); The result is: ["2 ", ", 2 Hours 10 Minutes"] This method seems useful to extract values like "days", "hours" and " ...

Issue: (SystemJS) Unable to find solutions for all parameters in $WebSocket: ([object Object], [object Object], ?)

Upon running the code snippet below, an error is thrown: Error: (SystemJS) Can't resolve all parameters for $WebSocket: ([object Object], [object Object], ?). app.component.ts import { Component } from '@angular/core'; import {$WebSocket} ...

An error in the floating point has occurred while attempting to generate prime numbers

My program is capable of generating prime numbers. The code functions as expected when I request the first 100 or 200 primes, but encounters a Floating Point Exception error when I attempt to generate prime numbers beyond 300. It appears that the issue l ...

What is the best way to manage the package-lock.json file during deployment from git using SSH?

In my deployment process, I utilize a Git repository to check code in. By using web hooks, a deployment script is triggered on the production server. Once connected to Git via SSH and a .pem key on the server, I perform a Git pull, npm install, webpack bui ...

Retrieve JSON data from my PHP API within my Laravel application

My scenario involves sending data using the Laravel HTTP client to a sample PHP API. The Laravel code I'm utilizing for this task is as follows: $p = 'img.jpg'; $path = storage_path('app' . DIRECTORY_SEPARATOR . &a ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

Check if the element with the ID "products" exists on the page using JQuery. If it does, then execute a certain action

Is there a way to create a conditional statement that executes if the element with the ID "products" is present in the HTML code? Thanks in advance for your help! Pseudo code using JavaScript (JQuery) if ( $('#products').length ) { // do s ...

Changing the background color of a page to match the background color of a button in React, which can be updated at any time

I have a special button called ArbitraryBtn that, when clicked, changes the page's background color to random colors: import React from 'react'; export const changeToArbitraryColor = () => (document.body.style.backgroundColor = ...

What could be the reason behind my useEffect() not triggering when updating a value in a React context?

How come my useEffect hook doesn't trigger when I update a dependency that involves a React context? In my project, the context is used within a wizard to gather user data and then process it on the final step. I am able to update the "Person" fields ...

Extract the links from the database using AngularJS

Currently, I am utilizing Laravel 5 for the backend and Angular.js for the frontend. The application operates solely through ajax requests. In my view, I have static links that are always visible on any page. Here is an example of how they are displayed: ...

AngularJS: engaging search experience

I'm just starting to learn AngularJS, and I have a project where I need to create an interactive search feature. So far, this is what I have: article/views/articles.html <form class="form-inline"> <div class="form-group"> < ...

Resolving the issue of nested modals within Bootstrap

I am experiencing some issues with my customer visits list page. When I try to add a visit, it opens a bootstrap popup ("#Pop1") to record the visit details. Within this modal, there is an option to add a new customer on the spot, which then triggers anoth ...

What is the process for transmitting images from React Native to native modules?

Challenge I am facing an issue trying to send an array of locally saved images from the JavaScript side (stored in an assets folder) to both iOS and Android native sides. The native code processes the images and returns a new image successfully when using ...

The data displayed in the <span> element isn't reflecting the response from the loaded page, despite being visible in Firebug

I have encountered a problem while trying to load a signup.php page into a div on my main page. All the elements (forms, JavaScript, etc.) function correctly in the loaded page, except for one issue - I cannot get the response from the PHP script to displa ...

Choosing a specific page number - kendo grid

Currently, I am working on creating a grid using kendo-telrik. Let's say I have 100 data items, but in the JSON format, I only have 10 data items (assuming each page contains 10 data items for pagination). However, I want to display all the pages (10 ...

Discovering the Modification of a Variable Value in angularJS

Within my HTML markup, I have the following input field: <input id="Search" type="text" placeholder="Search Images.." ng-model="data" ng-keypress="($event.charCode==13)? searchMore() : return"> This input field serves as a search bar for us ...

Saving integer data retrieved from DynamoDB in a React Native application

I need to store a user's progress by saving a value in a DynamoDB. While storing the value is not difficult, accessing this value for use in my application has proven to be quite challenging. When using dynamoDBWrapper.getItem(params), where the para ...

How can I rename attribute values in a dropdown menu and ensure they work properly?

I'm facing an issue with my code. How can I store the option values in a database when they have numbering like value="1" or value="2"? Can I change it to something like value="1000" and have the other select box change to value="250" when selected? ...

How can I prevent dataTable resizing?

Is there a solution to prevent datatable resizing? For instance, when the default number of rows per page in the datatable is set to 10 rows. If you input 13 rows into the datatable, it will be divided into 2 pages - with 10 rows on the first page and 3 ro ...