Show a list of fields in calculation fields if they are not blank
Hi there,
I have 10 number fields in an item: Book 1, Book 2, Book 3 and so on up to 10.
In a calculation field I would like to show a list of all the books that have number next to them, leaving out the books that don't have a number in its field, looking like this:
Book 1: 5
Book 2: 3
Book 8: 6
Book 9: 8
Book 10: 2
In the above, books 3, 4, 5, 6 and 7 in the podio item would be black, so not shown in the list.
I have played with a variety of IF statements but it's quickly gone beyond my brain. Any help would be amazing!
Thanks,
-
Hey Tim,
I would structure this using calculations that appear such as:
var b1 = @Book 1 ? "Book 1: " + @Book 1: "";
var b2 = @Book 2 ? "Book 2: " + @Book 2: "";
var b3 = @Book 3 ? "Book 3: " + @Book 3: "";
var b4 = @Book 4 ? "Book 4: " + @Book 4: "";
var b5 = @Book 5 ? "Book 5: " + @Book 5: "";
b1 + "\n" + b2 + "\n" + b3 + "\n" + b4 + "\n" + b5With the result appearing like:
For me, seeing it in real applications is more helpful than trying to read out the explanation, so I recorded this short video showing how I would approach this: https://www.loom.com/share/b4cfb5249de74f2eb9e5528cd0a04775
-
Hi Tim, hi Carson,
you must take care. If a field is emtpy you would get a blank line. e.g @Book 3 has no value - the result is:
Book 1: 5
Book 2: 3
Book 4: 6
Book 5: 8
but it should be:
Book 1: 5
Book 2: 3
Book 4: 6
Book 5: 8
without a blank line.
One option for resolving that is:
You keep the calculation except the last line. Add instead:var arr = [b1,b2,b3,b4,b5];
arr.filter(function (i) {return i != null;}).join("\n")Another option is another code like:
var arr = ["Book 1: " + @Book 1,"Book 2: " + @Book 2,"Book 3: " + @Book 3,"Book 4: " + @Book 4,"Book 5: " + @Book 5];
var lines = [];
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf(null) == -1){
lines.push(arr[i]);
}
};
lines.join("\n")Third option (which alos calculates a total line which returns the number of fields which have a value and the sum of all fields:
var obj = {"Book 1":@book 1,"Book 2":@Book 2,"Book 3":@Book 3,"Book 4":@Book 4,"Book 5": @Book 5};
var lines = [];
var sum = 0;
var numberBooks = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(obj[key] != null){;
lines.push(key + ": " + obj[key]);
sum += Number(obj[key]) || 0;
numberBooks += 1;
}
}
};
var totalLine = numberBooks + " Books: " + sum;
lines != "" ? lines.join() + "\n" + totalLine : ""If you don't need the total line remove var sum, var numberBooks and var totalLine from the code.
Rainer
Please sign in to leave a comment.
Comments
3 comments