3

Is it possible to unpack some of the keys of an object to a new object?

Let's say, I want to copy 3 of the keys (a, b, c) from test object to a new object (abc). Below mention code will work.

const test = {a:1, b:2, c:3, d:4, e:5 };
const {a, b, c} = test;
const abc = { a, b, c, f: 6};

Is there any approach with which I can do it in a single statement?

There is one more approach.

const test = {a:1, b:2, c:3, d:4, e:5 };
const abc = { ...test, f: 6};

But with this approach, I would later have to delete the unwanted keys (d, e in my case).

(Best Case Solution: If we don't have to keep track of unwanted keys. There can be n number of unwanted keys.)

Rahul Gandhi
  • 922
  • 10
  • 19
  • 2
    Just write a [helper function](https://ramdajs.com/docs/#pluck). Any reasonably named helper will likely be more readable than some super complicated destructure/restructure. – Jared Smith May 23 '18 at 12:19

3 Answers3

6

You can use object rest to destructure your initial object:

const test = {a:1, b:2, c:3, d:4, e:5 };
const {d, e, ...abc} = { ...test, f: 6};

console.log(abc);
bugs
  • 11,481
  • 5
  • 35
  • 48
2

If you know the specific keys you're going to need in the new Object, I would use good old Object.assign

const extendInfo = { //object containing properties to extend other object  }
const abc = { //your obj to extend }
Object.assign(abc, { a: extendInfo.a, b: extendInfo.b, c: extendInfo.c });

If you have a lot of props to extract the syntax becomes heavier and I would suggest a different approach, but if it's just a couple props, I think this is the cleaner and faster approach - and technically one line if you don't count variable declarations

Fabio Lolli
  • 749
  • 3
  • 22
1

Using destructuring the params and IIFE (Immediately invoked function expressions), we can get rid of the unwanted keys in the source objects.

const test = {a:1, b:2, c:3, d:4, e:5 };
const abc = (({a,b,c}) => ({a, b, c}))(test);
console.log(abc);

For ES5 compatibility,

var test = {a:1, b:2, c:3, d:4, e:5 };
    
var abc = (function (test) {
  return {
    a: test.a,
    b: test.b,
    c: test.c
  }
})(test);

console.log(abc);
Rahul Gandhi
  • 922
  • 10
  • 19