How to filter an array and remove some parameters from an object?

I have webcomponent that returns json, for example:

[{"name":"Jan", "lastname":"Kowalski", "role":"admin"},{"name":"Adam", "lastname":"Pietrzak", "role":"user"},{"name":"Karol", "lastname":"Kowalski", "role":"admin"},{"name":"Joanna", "lastname":"Wieczorek", "role":"user"}]

I need to write script service which:

  • gets this json from my form,
  • returns this json only for role=user and without info about role (I need only names and lastnames).

So effect should be:

[{"name":"Adam","lastname":"Pietrzak"},{"name":"Joanna","lastname":"Wieczorek"}]

This is my code:

function callService(context) {
	var data = context.getFirstParameter("data");
	data = data.filter(element => element.role === "user").map(element => {
		delete element["role"];
		return element;
	    });
	    
	return [{'selectedUsersFullListEnd': data}];
}

but it doesn’t work. Anyone knows why?

When you pass data to your script service you’ll always get string. So even if webcomponent returns object, your script service gets string, that’s why you need to add JSON.parse() and JSON.stringify() methods. Try:

function callService(context) {
	var data = context.getFirstParameter("data");
	data = JSON.parse(data);
	data = data.filter(element => element.role === "user").map(element => {
		delete element["role"];
		return element;
	    });
	    
 	return [{'selectedUsersFullListEnd': JSON.stringify(data)}];
}
2 Likes