0

I am creating a JS object, then stringifying it and trying to loop through the key-value pairs, but it is giving weird results. Please help.

var gv_array = {};
var gv_cookie_name = "_gv";
var gv_cookie_expiry = 1;
var $inv = jQuery.noConflict(); 

$inv('.product-image').bind('inview', function(event, isInView) {
   if (isInView) {
    var a = $inv(this).data('productid');       
    if(jQuery.inArray(a,gv_array) === -1){
        gv_array[a]=0;
    } 

    // Converting the array into JSON to save it to cookie

        var json_gv_arr = JSON.stringify(gv_array); 
        setCookie(gv_cookie_name,json_gv_arr,gv_cookie_expiry);

  }
});

$inv(document).ready(function(){
  setInterval('sendGV()',3000);
});

function sendGV(){
  var gv_cookie_val = getCookie(gv_cookie_name);
    gv_cookie_val = JSON.parse(gv_cookie_val);
   var gv_cookie_array = new Array();
      $inv.each( gv_cookie_val, function( key, value ) {
        if(value == 0){
               gv_cookie_array.push(key);
            }
     });
   alert(gv_cookie_array);
 }

The JS Object looks like this when i try to alert it.

 {"2234":0,"4563":0,"4555":0}

I need to send ids from the object whose value is 0 to insert into database and just after a receive the success msg from AJAX, i need to change the status of the ids in the object to 1.

UPDATE: Even after parsing the JSON string, it doesnt do anything.

segarci
  • 739
  • 1
  • 11
  • 19
coder101
  • 1,601
  • 2
  • 21
  • 41

2 Answers2

0

try as like following:

var data = {"2234":0,"4563":0,"4555":0};

$.each(data,function(key,value){
    console.log(key+":"+value);
})
Mahesh
  • 1,063
  • 1
  • 12
  • 29
0

Pure javacript:

data = {"2234":0,"4563":0,"4555":0};
keys = Object.keys(data);   // ["2234", "4563", "4555"]

for(i = 0; i < keys.length; i++){
  console.log(data[keys[i]]);   // 0, 0, 0
}

and for set the values:

for(i = 0; i < keys.length; i++){
  data[keys[i]] = 1
}

console.log(data); // Object { 2234=1,  4563=1,  4555=1}
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51