Store the value of a variable in an object

0

I have an interactive calendar, and to add new notes by clicking on the day I extract the format date of that day and store it in a variable, all right up there, the problem is that to be displayed in the Calendar as an "active note" I must add it to a predefined object called "events".

An example is the following:

events = { "2017-06-30": {"number": 5, } }; 
$('.responsive-calendar').responsiveCalendar('edit', events);

In the calendar, the box of June 30, 2017 already has a new event, with 5 tasks given by the "number". As seen in the image

Now with this code I program it with what was said at the beginning, nothing happens, place alerts with the values of the object "events":

$(".responsive-calendar").responsiveCalendar({
            onDayClick: function(events) {
                var keyy = $(this).data('year')+'-'+addLeadingZero($(this).data('month'))+'-'+addLeadingZero($(this).data('day'));
                events = { keyy : {"number": 5}};
            for (var keey in events) {
            if (events.hasOwnProperty(keey)) {
            alert(keey); // variable
            alert(events[keey]); // opcionales
        }
$('.responsive-calendar').responsiveCalendar('edit', events);

When doing the verification, it appears to me that the object is taking the name of the variable "keey" but not its value.

How do I resolve this?

    
asked by Davey - X 08.06.2017 в 02:28
source

1 answer

0

Since your JSON object consists of a value in a variable you must arm your object first as String and then pass it to JSON with the method JSON.parse () .

Example:

$(".responsive-calendar").responsiveCalendar({
 onDayClick: function(events) {
  var day = $(this).data('year')+'-'+addLeadingZero($(this).data('month'))+'-'+addLeadingZero($(this).data('day'));
  events = JSON.parse('{"'+ day +'": {"number": 5}}');
  for (var i in events) {
   if (events.hasOwnProperty(i)) {
    alert(i); // variable
    alert(events[i]); // opcionales
   }
  }
 }
});
$('.responsive-calendar').responsiveCalendar('edit', events);

For informative purposes and only to complement you can also use the method eval () .

Example:

  events = eval('{"'+ day +'": {"number": 5}}');

However, before using eval() it is important to keep the following in mind:
JSON .parse () vs eval ()

I hope this helps you! ;)) ...

    
answered by 08.06.2017 / 04:38
source