Say, I have an object:
const user = {_id: 1234, firstName: 'John', lastName: 'Smith'}
I want to create another object without the _id
key:
const newUser = {firstName: 'John', lastName: 'Smith'}
I am using this:
const newUser = Object.assign({}, {firstName: user.firstName, lastName: user.lastName})
Is there a better way to do this?
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object. assign supports only shallow copy.
assign() method. The Object. assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
You can achieve it with a form of destructuring:
const user = { _id: 1234, firstName: 'John', lastName: 'Smith' };
const { _id, ...newUser } = user;
console.debug(newUser);
However, at the time of writing this answer, the spread (...
) syntax is still at the ECMAScript proposal stage (stage 3), so it may not be universally available in practice. You may use it with a "transpilation" layer such as Babel.
Do it with Array#reduce
method with Object.keys
method.
const user = {
_id: 1234,
fistName: 'John',
lastName: 'Smith'
};
var res = Object.keys(user).reduce(function(obj, k) {
if (k != '_id') obj[k] = user[k];
return obj;
}, {});
console.log(res);
You are taking a shallow copy twice: once with the object literal, and again with Object.assign
. So just use the first of the two:
const newUser = {firstName: user.firstName, lastName: user.lastName};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With