Osman Goni Nahid
Osman Goni Nahid

Reputation: 1279

Cloning object with specific properties from object in javascript?

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.

Upvotes: 5

Views: 490

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

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.

Upvotes: 3

Mor Shemesh
Mor Shemesh

Reputation: 2889

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

Upvotes: 1

Related Questions