ketan
ketan

Reputation: 19341

Create array of object with condition

I am creating array of object. I want to add object based on condition. But, It add false instead of not adding object in array.

I tried:

const flag = false;
const list = [
      { key: 'abc', label: 'abcd' },
      flag && { key: 'bbb', label: 'abcd' },
      { key: 'ccc', label: 'abcd' },
      flag && { key: 'ddd', label: 'abcd' },
      { key: 'eee', label: 'abcd' },
   ];
   
console.log(list);

You can check output there are false in array.

Upvotes: 1

Views: 61

Answers (2)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6749

Assuming that all elements that are to be kept in the array do not have falsey values, you could simply filter them based on the value afterwards like so:

const flag = false;
const list = [
  { key: 'abc', label: 'abcd' },
  flag && { key: 'bbb', label: 'abcd' },
  { key: 'ccc', label: 'abcd' },
  flag && { key: 'ddd', label: 'abcd' },
  { key: 'eee', label: 'abcd' }
].filter(Boolean);
   
console.log("list:", list);

const flag2 = true;
const list2 = [
  { key: 'abc', label: 'abcd' },
  flag2 && { key: 'bbb', label: 'abcd' },
  { key: 'ccc', label: 'abcd' },
  flag2 && { key: 'ddd', label: 'abcd' },
  { key: 'eee', label: 'abcd' }
].filter(Boolean);

console.log("list2:", list2);

Upvotes: 2

Evan Trimboli
Evan Trimboli

Reputation: 30082

To do it all in a single statement, you can use the spread operator:

const list = [
  { key: 'abc', label: 'abcd' },
  ...(flag ? [{ key: 'bbb', label: 'abcd' }] : []),
  { key: 'ccc', label: 'abcd' },
  ...(flag ? [{ key: 'ddd', label: 'abcd' }] : []),
  { key: 'eee', label: 'abcd' },
];

It's pretty ugly though.

Upvotes: 2

Related Questions