Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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);

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

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));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda