-1

I need to get the value of the "id" property of the last element in array of JSON objects. I can find each element by id but I also need to get the value of last "id" in the array of JSON objects. In the example below it is '3'. Thanks in advance!

let types: any[] =
    [
        {'id': '0', 'value': ''},
        { 'id': '1', 'value': '' },
        { 'id': '2', 'value': '' },
        { 'id': '3', 'value': '' },
    ]; 

let index = 0;
let indexNext = 1;
types.forEach((item) => { 
    if (item.id == index) { 
        item.value = 'Book';
        console.log(item.value); //Book
    }
    if (item.id == indexNext) { 
        item.value = 'Magazine';
        console.log(item.value); //Magazine
    }
})
GGG
  • 125
  • 4
  • 12
  • How was this not closed as a dupe for 2 years? It was asked in 2010. [Get the last item in an array](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – Dan Dascalescu Apr 11 '22 at 21:18
  • @DanDascalescu Perhaps because ES2022 only became part of Typescript in Feb 2022? https://www.infoworld.com/article/3647880/typescript-46-adds-control-flow-analysis-es2022-support.html https://en.wikipedia.org/wiki/TypeScript#Release_history - I say this because you were advocating `array.at(-1)` in comments below. – JGFMK Apr 12 '22 at 06:00
  • @JGFMK: the accepted answer still uses ES3. Regardless of the answer, the question is a blatant dupe. – Dan Dascalescu Apr 12 '22 at 21:12
  • 1
    @DanDascalescu I fear you may often find that due to SO tagging saying Typescript and not JavaScript as well.. I am glad the post was here anyway - I learnt something with the `array.at()` syntax! ;-) – JGFMK Apr 13 '22 at 08:10

2 Answers2

1

types[types.length - 1] gives you the last element of types.

If you're calling forEach to do something with every item of the array and then do something different to the last one, the callback parameter to Array#forEach gets passed an index (as the parameter after the item). So you could write types.forEach((item, indexForItem) => { ... }); and then compare indexForItem to types.length - 1 to see whether you're on the last one or not.

  • the index parameter did the trick as well as types[types.length -1] Thanks a lot! Here is the code: `types.forEach((item, indexForItem) => { var t = types[types.length - 1]; if (t.id == indexForItem) { console.log('The last id is: ' + t.id); // The last id is: 3 } }); ` – GGG Mar 02 '20 at 18:45
0

Try this:

types[types.length - 1]['id']

JGFMK
  • 8,425
  • 4
  • 58
  • 92
  • That's even shorter. Thanks @JGFMK! – GGG Mar 02 '20 at 18:50
  • @GGG: the shortest is now [array.at(-1)](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – Dan Dascalescu Apr 11 '22 at 21:20
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at - a better link. Solution was buried on second page (mentions ES2022). https://stackoverflow.com/a/71242045/495157 – JGFMK Apr 12 '22 at 05:32