Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading