Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

Index of not working for a string value

anfield
Tera Guru

I have an issue finding a string in an array. Have confirmed via logging that the values in the array are strings, and the variable is of type string. Can someone help me with what I am missing?

 

function check_usage(all_users){

	var gdt = new GlideDateTime();
	gdt.addMonths(-2);
	var months_ago_format = gdt.getDate().getByFormat("yyyy-MM");
	var months_ago_str = JSON.stringify(months_ago_format);

	gs.log('Demand log: check usage: months ago: str ' + months_ago_str + typeof(months_ago_str));

	var obj_len = Object.keys(all_users).length;

	for (i=0; i< obj_len; i++){

			gs.log('Demand log: check usage: userid: ' + all_users[i].user_id + ' acc dates: ' + all_users[i].accrual_dates);
			
			var TF = all_users[i].accrual_dates.indexOf(months_ago_str);
			gs.log('Demand log: check usage: TF:' + TF);

	}

 

When I log the variable months_ago_str, the log looks like this

Demand log: check usage: months ago: str "2023-05"string

If I put that directly into the indexof brackets I can see that it is working, the log shows different index values for where the string is found. When I try and use the variable above though, it always produces -1.

 

The data itself looks like this. I am searching that array "accrual_dates". I think I am on the right track but something is throwing this off. 

Thanks in advance

 

Log Object: Demand Log: App Usage: all users3
Array of 10 elements
[0]: Object
user_id: string = user1
accrual_dates: Array of 1 elements
[0]: string = 2023-05
[1]: Object
user_id: string = user2
accrual_dates: Array of 5 elements
[0]: string = 2023-06
[1]: string = 2023-07
[2]: string = 2023-06
[3]: string = 2023-07
[4]: string = 2023-05
[2]: Object
user_id: string = user3
accrual_dates: Array of 1 elements
[0]: string = 2023-07

 

1 ACCEPTED SOLUTION

anfield
Tera Guru

Got this working by adding this line: var months_ago_str = String(months_ago_format);

 

The first few lines look like this now:

    var gdt = new GlideDateTime();

    gdt.addMonths(-2);

    var months_ago_format = gdt.getDate().getByFormat("yyyy-MM");

    var months_ago_str = String(months_ago_format);

 

No idea why it didnt like tostring or json.stringify

 

View solution in original post

5 REPLIES 5