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.

6
  • 3
    "Optimized" how? Runtime speed? Code clarity? Conciseness?CommentedJul 18, 2018 at 11:28
  • 2
    stackoverflow.com/q/51340819/9867451CommentedJul 18, 2018 at 11:31
  • @T.J.Crowder Thanks for too specific asking? Yeah my concern is Runtime speed firstlyCommentedJul 18, 2018 at 11:36
  • Are you really going to be doing this hundreds of thousands of times in a tight loop? Suggest writing the clear code first, and if you have a performance problem at some point that you've identified is down to this (which seems really unlikely), address it then.CommentedJul 18, 2018 at 11:41
  • I've done with clear code like I did with basic way. But curiosity !CommentedJul 18, 2018 at 12:02

2 Answers 2

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.

3
  • 1
    @ibrahimmahrir - Good find. The OP seems to be focussing on performance, whereas that focusses on elegance, but...that's a very thin distinction. :-)CommentedJul 18, 2018 at 11:40
  • Yeah I've just seen his comment.CommentedJul 18, 2018 at 11:41
  • 2nd approach is awesome but I'm not using ES2018. Liked that.CommentedJul 23, 2018 at 12:59
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

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.