2

Is there a way to destructure only some object properties in function arguments, while the rest would remain accessible in the object?

Consider the following react example. (I am using React as an example, but this question is applicable for JS in general)

const Form = (formProps) => {
  return (
    ...
    <FormSectionComponent
       initialValues={...} 
       values={...}
       {...formProps}
    />
    ...
  )
}

const FormSectionComponent = ({ initialValues, values}) => {
...
}

The incoming props are destructured in function arguments, however, there are other props coming in that I might want to access at some condition and which I do not want to or cannot destructure - for example I do not know what they are and would like to log them.

Is there a way not destructure the other props in the argument section and access them as a props object?

The only workaround I can think of is this:

const FormSectionComponent = (props) => {
  const { initialValues, values} = props;
}

But I wonder if there is any other solution.

1 Answer 1

6

You can do something like

const FormSectionComponent = ({ initialValues, values, ...props}) => {
...
}

which essentially binds props to the remaining properties of the argument that's passed to the function.

const f = ({a, b, ...rest}) => rest
console.log(f({a: 1, b: 2, c: 3, d: 4})) // { c: 3, d: 4}

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

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.