Search code examples
javascriptstring-concatenation

Javascript Concatenate Strings based on conditions


Is there a good way to accomplish this Javascript?

Basically I want something where the values of the fields are concatenate into a single field with comma between the values. Figure something simple like this

var a
var b
var c

allfieldvalue = a + ","b + ","c

My issue is I need to build condition in order for them to be put into allfieldvalue. So if var a = true, var b = false, and var c = true, then allfieldvalue = a +","c. Keep in mind, there could 20 different var. Hopefully that makes sense.


Solution

  • In case the goal is a string containing the names of variables that are true, use this approach:

    Make the variables into object props...

    var a = true;
    var b = false;
    var c = true;
    
    let object = { a, b, c };  // produces { a: true, b: false, c: true }
    

    Filter that object to exclude false values:

    object = Object.fromEntries(
      Object.entries(object).filter(([k,v]) => v) // produces { a: true, c: true }
    )
    

    Concat the keys:

    let string = Object.keys(object).join(',');  // produces "a,c"
    

    Demo

    var a = true;
    var b = false;
    var c = true;
    
    let object = { a, b, c }; 
    
    object = Object.fromEntries(
      Object.entries(object).filter(([k,v]) => v) 
    )
    
    let string = Object.keys(object).join(','); 
    console.log(string)