5

What is the optimized way to clone one object from another object with specific properties, not all?

Like below we can get values by projection from an object:

let tempObject = { 
  prop1 : 'something',
  prop2 : 'something' ,
  other : 'others'
};
//then
let { prop1, prop2} = tempObject;

Same way I want to clone a few properties from another object like

let oldObject = { 
  p1 : 'something',
  p2 : 'somethig',
  p3 : 'something' 
}

Want to make another object from above oldObject with only p1 and p2 those two properties. Expected newObject will be {p1 : 'something', p2 : 'somethig'}.

I know there are many ways to do that but I wanted to know the optimized way with the explanation.

Osman Goni Nahid
  • 1,193
  • 2
  • 15
  • 24

2 Answers2

3

I'd keep it simple:

let newObject = {
    p1: oldObject.p1,
    p2: oldObject.p2
};

That will also be very, very fast, as you've commented you're thinking in terms of performance.

You could complicate it with a loop:

let newObject = {};
for (const name of ["p1", "p2"]) {
    newObject[name] = oldObject[name];
}

Or with property rest (ES2018, in modern browsers, and supported by transpilers for a long time now) you could copy all but the ones you name:

let {p3, ...newObject} = oldObject;

But I'd keep it simple in most cases.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You can use lodash to select only the relevant properties with _.pick, like so:

_.pick(oldObject, ["p1", "p2"])

You can see a working version here: https://jsfiddle.net/W4QfJ/19493/

Or look at: Filter object properties by key in ES6

Mor Shemesh
  • 2,689
  • 1
  • 24
  • 36