Search code examples
javascriptdestructuring

Dynamic Object Destructuring


I'm trying to figure out a way to destructure an object based on a dynamic list/array of property names.

Say, I have an object:

let individual = {
    id: 1,
    fullname: 'User Name',
    sex: 'M',
    birthdate: new Date(1975, 3, 15)
};

and a dynamic array with property names:

let properties = ['id', 'fullname','sex'];

is there a way to simply get a resulting object with only the properties specified in the array:

{
    id: 1,
    fullname: 'User Name',
    sex: 'M'
}

Solution

  • I'm not sure if it can be done with destructuring, but it can be done simply with a couple of functions.

    let individual = {
      id: 1,
      fullname: 'User Name',
      sex: 'M',
      birthdate: new Date(1975, 3, 15)
    };
    let properties = ['id', 'fullname','sex'];
    
    let result = Object.fromEntries(properties.map(prop => [prop, individual[prop]]));
    
    console.log(result);