0

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"}]
1
  • If you have an array, and want to insert (or delete) elements in the existing array, you should take a look at Array.prototype.splice Commented May 25, 2024 at 7:22

1 Answer 1

0

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

const finalFieldList = [
 { "fieldName": "waldo" },
 ...(shortForm ? [shortFormFields] : longFormFields),
 { "fieldName": "xyzzy" }
];
Sign up to request clarification or add additional context in comments.

1 Comment

you don't need parentheses here, since the spread is syntax, not an operator

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.