1

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.

2
  • What condition exactly? Commented Aug 22, 2022 at 21:44
  • 3
    Don't use separate variables. Put them in an array and filter() to get all the true values. Then use .join() to concatenate them. Commented Aug 22, 2022 at 21:46

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

This is actually what I wanted. Based on field value condition being true, put all the variable name into one field. This is only my 3rd day of trying to learn Javascript and didn't even know these option. Thanks!
2

Put them in an array, then use .filter() and .join() to concatenate the true values.

let a = true;
let b = false;
let c = true;

let all_vars = [a, b, c];
let result = all_vars.filter(e => e).join(',');
console.log(result);

2 Comments

Produces 'true, true' which I think (I might be wrong) isn't the OP's intent. I think the OP wants 'a,c', which would suggest placing the vars in an object and filtering entires
That's what I suspect as well, but the question isn't clear about it.
0

First, It depends on what's in the variable, if you want a boolean and display it, you could do something like this :

function myFunc(...variables) {    
    console.log(variables.filter(v => v != false).join(", "));
}
let a = true;
let b = false;
let c  = true
console.log(myFunc(a,b,c));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.