Show a list of fields in calculation fields if they are not blank

Comments

3 comments

  • Carson Young - Red Cliff Labs

    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" + b5

    With 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

    1
    Comment actions Permalink
  • Tim Miller

    That's great, thank you!

    0
    Comment actions Permalink
  • Rainer Grabowski

    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

    0
    Comment actions Permalink

Please sign in to leave a comment.

Powered by Zendesk