0

Let's say that I got this from a JSON file.

[{
    "data": {
      "member": "Feufoe, Robert",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Hefo, Talia",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Mossler, John",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "McEvans, Nora",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  }
]

In my script, I want to query the properties of the last entry (in this case, the entry belonging to Nora McEvans) when defining different variables.

However, the file containing the above JSON is dynamic, constantly being added to. So I need the script to reference only the last entry every time.

How can I do this?

  • 2
    Possible duplicate of [Get the last item in an array](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – Mate Solymosi Jul 11 '17 at 18:29
  • Yeah, probably. I think mine's a bit more clear-cut, though, @MátéSolymosi. But I got my clear-cut answer, so delete this if you must. – solar_microwave_32 Jul 12 '17 at 05:41

2 Answers2

1

Just reference YOUR_ARRAY[YOUR_ARRAY.length - 1] Example:

var data = [{
    "data": {
      "member": "Feufoe, Robert",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Hefo, Talia",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Mossler, John",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "McEvans, Nora",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  }
];
console.log(data[data.length - 1]);
JakeBoggs
  • 274
  • 4
  • 17
1

Just to add what I think is a neater solution for the last item in an Array

var lastItem = data.slice(-1);

It's only better if you are following the maxim of less typing is better.

JSDBroughton
  • 3,966
  • 4
  • 32
  • 52