0

My server(PHP) response JSON object like this data:

{

    "0": {
        "action_id": "80",
        "action_transaction_id": "5743",
        "action_matched_email": "test_1@gmail.com",
        "action_by_user": "user1",
        "action_count": "0",
        "action_date": "2017-07-19 15:01:26"
    },
    "1": {
        "action_id": "1",
        "action_transaction_id": "1",
        "action_matched_email": "Admin@email.com",
        "action_by_user": "ADMIN",
        "action_count": "4",
        "action_date": "2017-07-19 15:10:08"
    },
    "new_count": {
        "action_count": "4"
    }
}

The data are not limited, sometimes server throws many data. It depends on what the condition is.

This is my ajax did after success:

success: function(data, status, jqXHR) {

   $.each(data, function(i, row) {


document.getElementById("hidden_counter").value = "";//new_count value here

   var allRows =window.parent.document.getElementsByClassName('row'+row.action_transaction_id+'');

   for (var i = 0; i < allRows.length; i++) {
       allRows[i].style.backgroundColor = '#008e00';
       allRows[i].style.color = '#f0fff0'; 
       //should exclude the last array when updating the bgcolor and style color of the row   
    }
  });
}

I have 2 things to know and do.

  1. How can I get the last object?

    "new_count": { "action_count": "4" }

so that I can update my hidden input value to it.

  1. How can I exclude the last object when updating the styles of rows?
apokryfos
  • 38,771
  • 9
  • 70
  • 114
c.k
  • 1,075
  • 1
  • 18
  • 35
  • 3
    This is not an array, this is an object with the properties `0` and `1`. – t.niese Jul 19 '17 at 07:35
  • 2
    If `data` represents the object above, and you want to access its property `new_count` then why don't you write `data.new_count` ? There is no _last_ element in an Object, because the sorting order of the properties is not defined, see: [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795) for more details. – t.niese Jul 19 '17 at 07:37
  • 1
    Assuming all keys will be numeric, you can try `var lastIndex = Math.max.apply(Object.keys(object).map(Number))` – Rajesh Jul 19 '17 at 07:39

6 Answers6

2

You shouldn't mixup pure js with jquery:

success: function(data, status, jqXHR) {

   $('#hidden_counter').val(data.new_count.action_count);

   $.each(data, function(i, row) {

     if (row.action_transaction_id === undefined) {
       return;
     }

     $('.row' + row.action_transaction_id).css({
         backgroundColor: '#008e00',
         color: '#f0fff0'
     });
  });
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
1

If your object name is lets say jsondata then for accesing new_count you can get it using,

jsondata.new_count

If you want to access last element then you can access it through ,

jsondata.new_count.action_count
Bhavin
  • 2,070
  • 6
  • 35
  • 54
1

How can I get the last object?

Object keys are not sorted and are retrieved in an order specific to browsers. So you can try to do is, get list of keys and take the maximum value.

As commented before, this should do the trick:

var lastIndex = Math.max.apply(null, Object.keys(object).map(Number))

How can I exclude the last object when updating the styles of rows?

You can either stop loop at length - 1

or you can try to use CSS selectors:

var selector = '.row' + row.action_transaction_id + ':not(:last-child)';
var allRows = window.parent.document.querySelectorAll(selector);

// OR since you are using jQuery

var allRows = $(window).parent().find(selector)

// OR
var selector = '.row' + row.action_transaction_id;
var allRows = $(window).parent().find(selector).not(':last-child')
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • 1
    It would have to be `Math.max.apply(undefined, Object.keys(object).map(Number))`, beside that this would return `NaN` for the given case because `Number('new_count')` will result in `NaN` – t.niese Jul 19 '17 at 07:54
  • @t.niese True. I always forget to pass context. Thanks! Updated answer – Rajesh Jul 19 '17 at 07:56
  • But it still would return `NaN` because the object does not only contain numeric values. – t.niese Jul 19 '17 at 08:04
0

first piece: get the element with greatest index (=length - 1)

second: loop all elements from index 0 until index < length-1

var lastArrayElement = allRows[allRows.length - 1];
var action_count = lastArrayElement.action_count;

// loop all but last element:
for(var i=0; i<allRows.length-1;i++){ 
   do_something(allRows[i]); //custom function
}

assumption:

  • the index is correct and not resorted in the process of creating json object
  • the index is indeed a range from 0 to some integer, without values left out

edit

indeed the allRows.length will not work as it is an object (containing pure numeric values as properties). Object.keys(allRows).length will give you the count van properties. However it will give you 3 as the last textual index is taken in the count as well.

var max = 0;
for(i = 0; i < Object.keys(allRows).length;i++) {

    if(parseInt(Object.keys(allRows)[i]) > max) {
        max = Object.keys(allRows)[i];
    }

}

the last element then will be in var lastArrayElement = allRows[max];

Ivo P
  • 1,722
  • 1
  • 7
  • 18
0

You can use Object.keys

success: function(data, status, jqXHR) {
      var lastKey = Object.keys(data)[Object.keys(data).length-1];
      $.each(data, function(i, row) {
           if (i== lastKey) { /* It's the last key */ }
          ...

Note that for older browsers you may need to use the polyfill included in that link.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

try this:

    $.each(data, function(i, row) {
            if(row["action_count"])
            {
                document.getElementById("hidden_counter").value = row["action_count"];
            }
            else
            {
                var allRows =window.parent.document.getElementsByClassName('row'+row.action_transaction_id+'');
                for (var i = 0; i < allRows.length; i++) {
                    allRows[i].style.backgroundColor = '#008e00';
                    allRows[i].style.color = '#f0fff0'; 
                }
            }
        });
Ganesan San
  • 174
  • 6