Looking to retrieve information stored in a JSON stringified object

Struggling with accessing the selected cell from an addListener event in Google Visualization Calendar is my current challenge. By utilizing

JSON.stringify(chart.getSelection());
, I am able to successfully print out the selected cell, which appears as [{"date":1468195200000,"row":0}].

The issue I am facing revolves around accessing the date object within this selection. My attempt to access it using the following code snippet:

var obj = JSON.stringify(chart.getSelection());
console.log('selected value ' + obj.date);

However, it outputs as Undefined. When I print out the obj, it presents as [object, object]. Any advice or direction on how to properly access this date object would be greatly appreciated. Please reach out if further information is required.

Answer №1

Utilizing JSON.stringify() allows for the serialization of a data object into string format. One can easily access the object directly following this serialization process.

Let data = chart.getSelection()[0]; // assuming only a single item exists in the selection array.
console.log(data.date)

Answer №2

Give this a shot:

let info = [{"date":1468195200000,"row":0}]

let rowSelection = info[0].row;
let dateSelection = new Date(info[0].date);

console.log(rowSelection);
console.log(dateSelection);

Answer №3

Be cautious when directly accessing the first element of an array while listening for the 'select' event.

chart.getSelection()[0]

The 'select' event is triggered both when a selection is made and when it is removed.

Therefore, the line above will encounter issues when the selection is removed.

Ensure to check the length before attempting to access the array.

  selection = chart.getSelection();
  // Verify the selection length
  if (selection.length > 0) {
    console.log(selection[0].date);
  } else {
    console.log('selection removed');
  }

Below is a functional snippet: select a date, then select again to remove the selection...

google.charts.load('current', {
  callback: function () {
    var dataTable = new google.visualization.DataTable();
    dataTable.addColumn({ type: 'date', id: 'Date' });
    dataTable.addColumn({ type: 'number', id :'Score' });
    dataTable.addRows([
      [ new Date(2016, 3, 13), 101 ],
      [ new Date(2016, 3, 14), 102 ],
      [ new Date(2016, 3, 15), 103 ],
      [ new Date(2016, 3, 16), 104 ],
      [ new Date(2016, 3, 17), 105 ]
    ]);

    var chart = new google.visualization.Calendar(document.getElementById('chart_div'));
    google.visualization.events.addListener(chart, 'select', function () {
      var selection = chart.getSelection();

      // Verify the selection length
      if (selection.length > 0) {
        console.log(selection[0].date);
      } else {
        console.log('selection removed');
      }
    });
    chart.draw(dataTable);
  },
  packages:["calendar"]
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Answer №4

There's a single object in this array of objects, I believe. To access its date property, use console.log(obj[0].date); instead!

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

Sharing socket data between different namespaces in Socket.ioSocket.io enables the

Is there a solution to sharing data set in a socket in one namespace and accessing it on another namespace? While I understand that data can be attached to the socket object itself, a problem arises when trying to access the data in a different namespace. ...

Reading a JSON file stored within the project directory on iPhone PhoneGap using JavaScript

I need to access a JSON file stored in a project folder. Currently, I am using the following code: var obj = "www/places.json"; Can someone help me figure out how to read a JSON file located in the project folder www when working with iPhone PhoneGap an ...

What is the best approach for implementing form validation that is driven by directives in AngularJS?

Currently, I am working on creating a registration form using AngularJS. I need to use the same form in four different sections. To achieve this, I have created a common form within a single HTML page as shown below: <div> <div> < ...

Check if the provided user email is already in use using the express validator

I have configured the following route in my Node.js API application: const { body } = require("express-validator"); router.post( "/user/signup", [ body("firstName").not().isEmpty().withMessage("First name is required"), body("lastName").not().i ...

Listener for clicking on a marker in Google Maps

Trying to add a click event to Google Map markers in my Cordova app has proven to be quite challenging. The recommended ways mentioned in the documentation don't seem to work, unless I make the marker draggable - which is not an option for me. It seem ...

Steps to deactivate two choices in a multi-select dropdown menu and visually dim those options

Hey there, I recently worked with Angular8 and Bootstrap 4. I utilized a Bootstrap multi-select dropdown, where I encountered an issue: specifically, I'm trying to disable and gray out the options for PL Marketing and CL Marketing but have been unsucc ...

How to extract data from a JSON file in Java without relying on org.json library

I need help extracting the first element in the "key" array and its corresponding value from the given JSON data. I have come across examples using org.json, but it seems outdated. Can anyone suggest the best way to achieve this with the provided JSON file ...

I am encountering an issue where I am unable to send a HashMap String to a PHP server, and I am not receiving a JSONArray in the

How can I send a hashmap string to a PHP server without receiving back a JsonArray using Volley in Android? CM =$_POST['code_send']; $db =Db::getInstance(); $records = $db->query ("SELECT * FROM p_users WHERE c_meli='$CM'"); $js ...

Loading information from JSON document using AJAX

I am currently in the process of developing a sports website and I need to retrieve JSON data from . To achieve this, I have implemented an ajax call in my page with the following script: <div id="data"></div> <script> $.ajax({ ...

Uh-oh! The module "side-channel" cannot be found. An error occurred in the loader with code 936 when trying to run the command "npm start"

During the execution of npm start to view my React app, I encountered the following error: > react-scripts start node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'side-channel' Require stack: - C:\Users&bs ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

Displaying a MySQL blob image in an HTML file with Vue.js: A step-by-step guide

Here is a Vue file that I have: export default { data(){ return{ info: { name: '', image: '', }, errors: [] } }, created: function(){ thi ...

Learning how to extract subarray values from JSON in Android is determined by the specific item chosen

I've got a JSON file structured like this: [ { "category" : "Category - 1", "table":[ { "id" : 1, "title" : "Sample Title 1" }, { "id" : 2, ...

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

Having trouble with jQuery show/hide not functioning properly?

My website has a sub-menu section with a shopping cart icon. When a user hovers over the icon, it reveals a hidden cart section. The user can then move the mouse into the cart section to remove items. The problem I'm facing is that if a user displays ...

Fresh Redux shop in stealth mode

I am managing a Single Page Application using React and Redux. Some customers have expressed interest in keeping two separate instances open with distinct credentials (one in normal view and one in incognito mode on Chrome). As both instances can access t ...

clear JavaScript array of elements

I've been grappling with this issue for hours now, and it seemed so straightforward at first; My goal with JavaScript is to iterate through an array, retrieve the current index value, and then remove that value from the array. I've read that spl ...

Aggregate the data entered into input fields on one page and display them on a separate page

Can you help me with this task? - I have 2 pages set up (page 1 has input fields & page 2 is where the entered data should be displayed) - I want to retrieve all the text input from the first field and insert it into the "content" tag on the second page. ...

avoid inserting into a specific field with a specific name

I am trying to add a picture next to a specific name, but I am facing issues as there is no option for inserting it. This is how my table looks: https://i.sstatic.net/RRaTb.png How can I insert a picture in front of a particular name? The content of my ...

Oops! Looks like node.js is throwing an error with the message "connect ECONNREFUSED"

After creating a node.js application that interacts with a locally installed MySQL database, I encountered an issue where running the app through CMD (npm start) returned the desired results, but testing it through Postman resulted in an error: connect E ...