Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!