Samreaksa Ros

Web Developer - iOS Developer

Getting the last item in a Javascript object

Get the last object by counting length of array index

const countries = [ 
  { "id": "1", "name": "Cambodia", "code": "kh", "phonecode": "+855", "__typename": "Country" }, 
  { "id": "2", "name": "Vietnam", "code": "vn", "phonecode": "+84", "__typename": "Country" }, 
]
const getArrayIndex = Object.keys(countries);
const lastIndex = getArrayIndex.length - 1;
console.log(countries[lastIndex]);

Get the last object by adding one more element to the beginning of an array

const countries = [ 
  { "id": "1", "name": "Cambodia", "code": "kh", "phonecode": "+855", "__typename": "Country" }, 
  { "id": "2", "name": "Vietnam", "code": "vn", "phonecode": "+84", "__typename": "Country" }, 
]
const lastInex = Object.keys(countries).unshift();
console.log(countries[lastInex -1]);

Get the last object by removing the last element from an array

const countries = [ 
  { "id": "1", "name": "Cambodia", "code": "kh", "phonecode": "+855", "__typename": "Country" }, 
  { "id": "2", "name": "Vietnam", "code": "vn", "phonecode": "+84", "__typename": "Country" }, 
]
const lastInex = Object.keys(countries).pop();
console.log(countries[lastInex]);