Search code examples
javascriptobjectecmascript-6destructuring

How can I get object from another object, only with needed keys?


I have one strange question about Destructuring in the JS. How can I get object from another object, only with needed keys. For example, to transform this object:

let firstObj = {
    a: 1,
    b: 2,
    c: 3,
    d: 4
};

To this:

let secondObj = {
    a: 1,
    d: 4
};

I have array with first type objects. For some reasons I should to use minimal code for this. My minimum code:

arrayObj = [firstObj, firstObj, firstObj, firstObj, firstObj];
let secondArr = arrayObj.map(
  ({a, d}) => ({a, d})
);

How can I improve this one?


Solution

  • You could use an IIFE for takeing the wanted properties and return a new object.

    var first = { a: 1, b: 2, c: 3, d: 4 },
        second = (({ a, d }) => ({ a, d }))(first);
    
    console.log(second);

    With an array of keys for a dynamic approach

    var first = { a: 1, b: 2, c: 3, d: 4 },
        keys = ['a', 'd']
        second = Object.assign(...keys.map(k => ({ [k]: first[k] })));
    
    console.log(second);