Home > database >  JS Add to array with Spread Operator if non-NULL - Expression Syntax
JS Add to array with Spread Operator if non-NULL - Expression Syntax

Time:10-21

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]}
      } 

CodePudding user response:

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

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related