Reputation: 895
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.
Upvotes: 2
Views: 1846
Reputation: 15313
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}
Upvotes: 6