1

I define an array like this:

[{foo:0}, true === false && { foobar:1}, {bar:2}]

My expected result would be that the middle item is not added at all when the middle condition is not met:

[ { foo: 0 }, { bar: 2 } ]

in fact it adds false as an array item:

[ { foo: 0 }, false, { bar: 2 } ]

Is there a way to prevent adding the false while maintaining this lightweight syntax (I know I could always use push or the spread operator)

3
  • 2
    Nope, there's no such syntax in JavaScript. Commented Mar 15, 2018 at 14:58
  • But if you want to keep your building terse you could just filter after: [{foo:0}, true === false && { foobar:1}, {bar:2}].filter(Boolean) Commented Mar 15, 2018 at 14:59
  • You could use a ternary like condition ? { foobar:1} : null and filter out null values at the end. Commented Mar 15, 2018 at 15:00

2 Answers 2

3

You could use concat with spread syntax and an empty array as neutral value.

var a = [].concat(...[
        { foo: 0 },
        true === false ? { foobar: 1 } : [],
        { bar: 2 }
    ]);

console.log(a);

With apply

var a = Array.prototype.concat.apply([], [
        { foo: 0 },
        true === false ? { foobar: 1 } : [],
        { bar: 2 }
    ]);

console.log(a);

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

Comments

0

As Denys suggested, you could do this:

const arr = [{foo:0}, true === false && { foobar:1}, {bar:2}].filter(el => el !== false);
console.log(arr);

2 Comments

el => el !== false? Please make it less verbose.
Less verbose? What do you suggest, !!el? Sorry, but the OP only wants to remove false values, nor 0, null or empty strings.

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.