简体   繁体   中英

Get final 2 data in json_encode output

I'm bring json_encode data. The output looks as below

[{"ab":"item1"},{"ab":"item2"},{"ab":"item3"},{"tg":"int1"},{"int":"int2"}]

I fetch the data as

$.post('add.php',
    { },
    function(data){ 
       var tot = data.length-2;
       for(i = 1; i<tot; i++){
           console.log( data[i].ab ) //ab data fetched here
       }
    }
);

My question is, how do I get the final 2 data (referred as int1 and int2 in my example above)?

NOte: The data length varies

Try this:

var lastTwo = data.slice(data.length - 2);

Fiddle

If you don't know the key of those objects:

for (var i = 0; i < lastTwo.length; i++)
{
    var a = Object.keys(lastTwo[i]);
    var value = lastTwo[i][a[0]];
}

Fiddle

You can use pop twice, to get the last two items.

var data = [{"ab":"item1"},{"ab":"item2"},{"ab":"item3"},{"tg":"int1"},{"int":"int2"}];

var last = data.pop(),
    secondLast = data.pop();

// As keys of the object are not fixed, use Object.keys
var lastItem = last[Object.keys(last)[0]];
var secondLastItem = secondLast[Object.keys(secondLast)[0]];

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM