Search code examples
javascriptecmascript-6ecmascript-2016ecmascript-nextecmascript-2017

What's the shortest way to copy only selected attributes in JavaScript?


Given the following two objects:

let a = { foo: 'bar' };

let b = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7
};

We can assume that all values within these objects are primitives. The goal is to copy some attributes from object b to object a, but not all.

Example:

a.one = b.one;
a.two = b.two;
// Do not copy item three
a.four = b.four;
a.five = b.five;
a.six = b.six;
// Do not copy item seven

In this example we have omitted attributes 3 and 7 but we could also omit any other attribute or even more than just two items. As you can see this solution can be quite cumbersome if we are dealing with many attributes.

Question: What's the shortest , cleanest and most simple solution to achieve something like this with modern JavaScript in 2021?

Note: For the solution you can assume there is an array of strings given. Each string represents a key of a value that should be copied. So, in the example above you can assume const keys = ['one', 'two', 'four', 'five', 'six']; being given.


Solution

  • I would use a forEach on the array of given keys to copy what I need:

    const a = {
      foo: 'bar'
    };
    
    const b = {
      one: 1,
      two: 2,
      three: 3,
      four: 4,
      five: 5,
      six: 6,
      seven: 7
    };
    
    const doCopy = ['two', 'five'];
    
    doCopy.forEach(el => a[el] = b[el]);
    
    console.log(a);