1

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.

3
  • flag && { key: 'bbb', label: 'abcd' }, always returns a value. And the value is the result of the expression. If you don't want to add something, then your best bet is a simple if(flag) list.push({ key: 'bbb', label: 'abcd' });. You can also do it as part of the array initialisation but it's too much of a hassle. Commented Nov 12, 2020 at 11:11
  • @VLAZ Yeah, but that add object to last. I don't want to change order. Commented Nov 12, 2020 at 11:19
  • Yes, I was just trying to not too much code in the comment, as it's hard to read. I thought it would be clear that you need to change how the array is populated to list.push({ key: 'abc', label: 'abcd' }); if (flag) list.push({ key: 'bbb', label: 'abcd' }); list.push({ key: 'ccc', label: 'abcd' }); if (flag) list.push({ key: 'ddd', label: 'abcd' }); list.push({ key: 'eee', label: 'abcd' }) Commented Nov 12, 2020 at 11:24

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I thought the question was tagged as typescript. This approach is more legible for sure.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.