Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to copy some properties from an object in JavaScript?

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?

like image 269
dpkwhan Avatar asked Nov 12 '16 12:11

dpkwhan


People also ask

How do you copy properties from one object to another in JavaScript?

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.

What is the most efficient way to deep clone an object in JavaScript?

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.

Which method is used to copy the value of an object?

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.


3 Answers

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.

like image 106
madox2 Avatar answered Oct 19 '22 16:10

madox2


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);
like image 43
Pranav C Balan Avatar answered Oct 19 '22 17:10

Pranav C Balan


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};
like image 22
trincot Avatar answered Oct 19 '22 16:10

trincot