inceon
inceon

Reputation: 5

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?

Upvotes: 0

Views: 70

Answers (2)

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

You can create a array with your needed keys and use reduce() on that array to get values from firstObj.

DEMO

const neededKeys = ['a', 'd'],
      firstObj = {a: 1,b: 2,c: 3,d: 4};

let result = neededKeys.reduce((r, v) => Object.assign(r,{[v]:firstObj[v]}), {});

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386624

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);

Upvotes: 4

Related Questions