MPummel
MPummel

Reputation: 55

Pulling last value in json file

I have a json file and I need to pull the last value from a particular customer id. The Json file is updated throughout the day and I have this setup to just be a function that will pull the last job number within the customer ID.

Json

[{"CustId":"5886708366","JobNumber":"636275400282798443c"},{"CustId":"123456798","JobNumber":"636275400535607074c"},{"CustId":"5886708366","JobNumber":"636275413000246135c"},{"CustId":"5886708366","JobNumber":"636275415626921919c"},{"CustId":"5926680270","JobNumber":"636275435491908861c"},{"CustId":"5926680270","JobNumber":"636275436824699429c"},{"CustId":"5926680270","JobNumber":"636275440818384096c"}]

I only need to pull from customer ID 5886708366 and use the last jobnumber in this case 636275415626921919c.

I have so far I have the following.

var picarioAPI = "where I pull the json file";

$.getJSON(picarioAPI, function (json) {
  for (i in json) 
    if (json[i].CustId == {{ customer.id }}) { 

I'm stuck on getting the last part. I'm able to loop through the jobs but cant just call just that last one. Any help would be great.

Upvotes: 0

Views: 162

Answers (3)

buræquete
buræquete

Reputation: 14698

The way to fetch last of the requested CustId within your array is as follows;

var json = JSON.parse('[{"CustId":"5886708366","JobNumber":"636275400282798443c"},{"CustId":"123456798","JobNumber":"636275400535607074c"},{"CustId":"5886708366","JobNumber":"636275413000246135c"},{"CustId":"5886708366","JobNumber":"636275415626921919c"},{"CustId":"5926680270","JobNumber":"636275435491908861c"},{"CustId":"5926680270","JobNumber":"636275436824699429c"},{"CustId":"5926680270","JobNumber":"636275440818384096c"}]');
var lastObj = json.reverse().find(obj => obj.CustId == "5926680270");
console.log(lastObj.JobNumber);

Reverse the JSON array, find the object with your customerId, and fetch its jobNumber, very straightforward one-liner.

Upvotes: 1

wharkins3
wharkins3

Reputation: 56

Try looping through your array in reverse to get the most recent.

for (var i = length - 1; i > 0; i--) {
  if (json[i].CustId == {{ customer.id }}) { 
  }
}

Upvotes: 1

pizzarob
pizzarob

Reputation: 12059

If you know for sure that you will only need the last item you could get it like this:

var lastItem = json[json.length - 1];

If you know the customer ID before hand you could use the find method, which would better if the customer might not always be at the last position of the array

var customer = json.find(val => val.CustId === '5926680270')

Upvotes: 1

Related Questions