Community Tip - Need to share some code when posting a question or reply? Make sure to use the "Insert code sample" menu option. Learn more! X
Hi,
I create a native javascript function to convert a infotable to a key-object holder:
================
function infoTableToKeyHolder(infoTable, keyField){
let holder = {};
for(let i = 0 ; i < infoTalbe.length; i++){
let item = infoTable[i];
let keyValue = infoTable[keyField];
holder[keyValue] = item;
return holder
}
}
=================
How to share the function for any JavaScript service ?
Regards,
Sean
Hello @seanccc
to use your function in other services you can make your function a service itself. Just use the "infoTable" and "keyField" as inputs and the return value as output.
To call your service in another service you just need to use the entity on which you created the service on.
e.g. Things["Thingname"].yourServiceName(infoTable, keyField);
and just a tip for your code:
you should return your value outside of your for-loop or else the loop will exit after the first iteration. so the code in your service should look more like this:
for(let i = 0 ; i < infoTable.length; i++){
let item = infoTable[i];
let keyValue = infoTable[keyField];
holder[keyValue] = item;
}
result = holder;
@lbisax ,
Thank you for pointing out the the code error, it's not production code, I just typed them in the post so didn't check it carefully.
But what's the return type of the service should be ? If return as JSON, then I have to do serialize in the service and de-serialize in the caller , it would cause additional performance loss.
Regards,
Sean