Getting a subset of properties from an object with destructuring and the spread operator
In response to yesterday’s article on object destructuring, someone asked how to get the rest of the properties that you didn’t destructure into variables as their own object.
For example, if you have an object like this…
let movies = {
disney: 'Moana',
pixar: 'Up',
dreamworks: 'How to Train Your Dragon',
nickelodeon: 'Wonder Park'
};
How do you pull disney
and pixar
into their own variables, and create an object with dreamworks
and nickelodeon
?
For that, we can combine object destructuring with the spread operator. Prefix one last variable with three dots (...
), and it will be assigned an object with the remaining properties of your object that weren’t destructured.
let {disney, pixar, ...everyoneElse} = movies;