Search code examples
javascriptarraysjavascript-objectsconditional-operatorternary

Inserting Javascript array elements into another array with ternary operator


I have an array of objects where each object defines a field in a React form. I want to display different sequence of fields depending on a boolean state. This means that I need to insert either one object or three objects into the array at a specific index. Works for a single object, but I am struggling to figure out how to insert multiple objects.

const [shortForm] = useState(false);

const shortFormFields = {"fieldName":"foo"}

const longFormFields = [
      {"fieldName":"bar"},
      {"fieldName":"baz"},
      {"fieldName":"qux"}]


const finalFieldList = [
      {"fieldName":"waldo"},
      shortForm === true? shortFormFields : INSERT-BAR-BAZ-QUX-HERE,
      {"fieldName":"xyzzy"}]

Solution

  • You can use the spread synatx (...) along with the conditional (ternary) operator.

    const finalFieldList = [
     { "fieldName": "waldo" },
     ...(shortForm ? [shortFormFields] : longFormFields),
     { "fieldName": "xyzzy" }
    ];