Search code examples
javascriptecmascript-6destructuring

Selectively Destructure an object, based on key name


Let's say I have this object:

const someProps = { darkMode: true, underlineMistakes: false, spellingView: (...), grammerView: (...) };

I do not necessarily know the names of any of the props, except that 1+ end in 'View'.

and I want to only destructure the keys that end in 'view', which I'd like to do something like:

const propsEndingInView = Object.keys(someProps).filter(prop => !prop.endsWith('View');
const {
  ...nonViewProps, // darkMode, underlineMistakes
  propsEndingInView // {spellingView: (...), grammerView: (...)}
} = someProps; 

I need to somehow separate the two kinds of props, preferably while

I can't think how to do this, or even if it's possible.


Solution

  • Destructuring is just way to get the properties you already know. You can't do this with destructuring. You can create a custom method to filter out the keys to get a subset of the object

    const someProps = {
      darkMode: true,
      underlineMistakes: false,
      spellingView: 'spellingView',
      grammerView: 'grammerView'
    };
    
    const subset = Object.fromEntries(
      Object.entries(someProps).filter(([k]) => k.endsWith('View'))
    )
    
    console.log(subset)