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.
-
3"Optimized" how? Runtime speed? Code clarity? Conciseness?T.J. Crowder– T.J. Crowder2018年07月18日 11:28:37 +00:00Commented Jul 18, 2018 at 11:28
-
2stackoverflow.com/q/51340819/9867451ibrahim mahrir– ibrahim mahrir2018年07月18日 11:31:18 +00:00Commented Jul 18, 2018 at 11:31
-
@T.J.Crowder Thanks for too specific asking? Yeah my concern is Runtime speed firstlyOsman Goni Nahid– Osman Goni Nahid2018年07月18日 11:36:45 +00:00Commented Jul 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.T.J. Crowder– T.J. Crowder2018年07月18日 11:41:32 +00:00Commented Jul 18, 2018 at 11:41
-
I've done with clear code like I did with basic way. But curiosity !Osman Goni Nahid– Osman Goni Nahid2018年07月18日 12:02:54 +00:00Commented Jul 18, 2018 at 12:02
2 Answers 2
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.
-
1@ibrahimmahrir - Good find. The OP seems to be focussing on performance, whereas that focusses on elegance, but...that's a very thin distinction. :-)T.J. Crowder– T.J. Crowder2018年07月18日 11:40:39 +00:00Commented Jul 18, 2018 at 11:40
-
Yeah I've just seen his comment.ibrahim mahrir– ibrahim mahrir2018年07月18日 11:41:22 +00:00Commented Jul 18, 2018 at 11:41
-
2nd approach is awesome but I'm not using ES2018. Liked that.Osman Goni Nahid– Osman Goni Nahid2018年07月23日 12:59:34 +00:00Commented Jul 23, 2018 at 12:59
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