Question
Task: Concatenate values from different fields into a single string using a separator, such as a comma. For example, there are several fields: #city
, #street
, #name
, #surname
, #nickname
.
Sometimes not all fields are filled, resulting in duplicate commas, like: City, , Vasily, , Vasea
.
Or sometimes it ends up like: , , , , Vasea
.
I thought about using strSplit, but I couldn't figure it out with this function.
= : str`#books + $if{var: "field" = "books"} + #first_attempt + $if{var: "field" = "first_attempt"} + #second_attempt`
if: if(condition: #$field != ""; then: ", "; else: "")
field: $#field
produces an error. I can't figure out where to fix it. #$field
, $#field
?
Logically, I understand what it should be, but the code... why #$field has a hash in front and here $#name - after the dollar sign
Answer
The most effective approach is to create a list of the required fields, filter out the empty values, and convert it into a string using listJoin:
=: listJoin(list: $filtered_list; str: ", ")
filtered_list: listFilter(list: $list; key: "value" != "")
list: listCreate(item: #city; item: #street; item: #name; item: #surname; item: #nickname)