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

181
Visualizações
JS Add to array with Spread Operator if non-NULL - Expression Syntax

I need to get an array resulting from the original array props.ids and conditionally (if not NULL) the variable selectedId appended. The following works, but the syntax doesn't look right. I need the selectedId && to check for non-NULL, and if so add selectedId. Is there a better syntax for this small expression?

const [selectedId, setSelectedId] = useState(null);

obj = {
        'exclude':[...props.ids, selectedId && selectedId]}
      } 
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In one line way

const [selectedId, setSelectedId] = useState(null);

obj = {
        exclude:[...props.ids, ...(selectedId === null ? [] : [selectedId])]}
      } 

Proper way

const [selectedId, setSelectedId] = useState(null);

obj = {
        exclude: [...props.ids]
      }

if (selectedId !== null) {
    obj.exclude.push(selectedId)
}
about 4 years ago · Juan Pablo Isaza Relatório

0

In addition Ananth's answer, you could also use the ternary operator inline

const ids = [1, 2, 3];

let item = null;
let resultWhenNull = [...ids, ...(item ? [item] : [])];
console.log(resultWhenNull);

item = 4;
const resultWhenNonNull = [...ids, ...(item ? [item] : [])];
console.log(resultWhenNonNull);

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use Ternary operator or a simple if statement to accomplish this

const [selectedId, setSelectedId] = useState(null);

const obj = {};

// if selectedId is present append selectedId, else return array of props.ids
obj['exclude'] = selectedId ? [...props.ids, selectedId] : [...props.ids]

const value = false;
const props = [1, 2, 3];
const valToAppend = 4;
const obj = {};
obj['test'] = value ? [...props, valToAppend] : [...props];

console.log(obj);

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