Copy specific properties from one object to another JavaScript

One of the fundamental differences of objects versus primitives is that objects are stored and copied “by reference”, whereas primitive values: strings, numbers, booleans, etc – are always copied “as a whole value”.

That’s easy to understand if we look a bit under the hood of what happens when we copy a value.

Let’s start with a primitive, such as a string.

Here we put a copy of

let user = {
  name: "John"
};
7 into
let user = {
  name: "John"
};
8:

let message = "Hello!";
let phrase = message;

As a result we have two independent variables, each one storing the string

let user = {
  name: "John"
};
9.

Quite an obvious result, right?

Objects are not like that.

A variable assigned to an object stores not the object itself, but its “address in memory” – in other words “a reference” to it.

Let’s look at an example of such a variable:

let user = {
  name: "John"
};

And here’s how it’s actually stored in memory:

The object is stored somewhere in memory (at the right of the picture), while the

let user = { name: "John" };

let admin = user; // copy the reference
0 variable (at the left) has a “reference” to it.

We may think of an object variable, such as

let user = { name: "John" };

let admin = user; // copy the reference
0, like a sheet of paper with the address of the object on it.

When we perform actions with the object, e.g. take a property

let user = { name: "John" };

let admin = user; // copy the reference
2, the JavaScript engine looks at what’s at that address and performs the operation on the actual object.

Now here’s why it’s important.

When an object variable is copied, the reference is copied, but the object itself is not duplicated.

For instance:

let user = { name: "John" };

let admin = user; // copy the reference

Now we have two variables, each storing a reference to the same object:

As you can see, there’s still one object, but now with two variables that reference it.

We can use either variable to access the object and modify its contents:

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference

It’s as if we had a cabinet with two keys and used one of them (

let user = { name: "John" };

let admin = user; // copy the reference
3) to get into it and make changes. Then, if we later use another key (
let user = { name: "John" };

let admin = user; // copy the reference
0), we are still opening the same cabinet and can access the changed contents.

Two objects are equal only if they are the same object.

For instance, here

let user = { name: "John" };

let admin = user; // copy the reference
5 and
let user = { name: "John" };

let admin = user; // copy the reference
6 reference the same object, thus they are equal:

let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true

And here two independent objects are not equal, even though they look alike (both are empty):

let a = {};
let b = {}; // two independent objects

alert( a == b ); // false

For comparisons like

let user = { name: "John" };

let admin = user; // copy the reference
7 or for a comparison against a primitive
let user = { name: "John" };

let admin = user; // copy the reference
8, objects are converted to primitives. We’ll study how object conversions work very soon, but to tell the truth, such comparisons are needed very rarely – usually they appear as a result of a programming mistake.

Const objects can be modified

An important side effect of storing objects as references is that an object declared as

let user = { name: "John" };

let admin = user; // copy the reference
9 can be modified.

For instance:

const user = {
  name: "John"
};

user.name = "Pete"; // (*)

alert(user.name); // Pete

It might seem that the line

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference
0 would cause an error, but it does not. The value of
let user = { name: "John" };

let admin = user; // copy the reference
0 is constant, it must always reference the same object, but properties of that object are free to change.

In other words, the

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference
2 gives an error only if we try to set
let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference
3 as a whole.

That said, if we really need to make constant object properties, it’s also possible, but using totally different methods. We’ll mention that in the chapter Property flags and descriptors.

So, copying an object variable creates one more reference to the same object.

But what if we need to duplicate an object?

We can create a new object and replicate the structure of the existing one, by iterating over its properties and copying them on the primitive level.

Like this:

let user = {
  name: "John",
  age: 30
};

let clone = {}; // the new empty object

// let's copy all user properties into it
for (let key in user) {
  clone[key] = user[key];
}

// now clone is a fully independent object with the same content
clone.name = "Pete"; // changed the data in it

alert( user.name ); // still John in the original object

We can also use the method Object.assign.

The syntax is:

Object.assign(dest, ...sources)

  • The first argument
    let user = { name: 'John' };
    
    let admin = user;
    
    admin.name = 'Pete'; // changed by the "admin" reference
    
    alert(user.name); // 'Pete', changes are seen from the "user" reference
    4 is a target object.
  • Further arguments is a list of source objects.

It copies the properties of all source objects into the target

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference
4, and then returns it as the result.

For example, we have

let user = { name: "John" };

let admin = user; // copy the reference
0 object, let’s add a couple of permissions to it:

let user = { name: "John" };

let permissions1 = { canView: true };
let permissions2 = { canEdit: true };

// copies all properties from permissions1 and permissions2 into user
Object.assign(user, permissions1, permissions2);

// now user = { name: "John", canView: true, canEdit: true }
alert(user.name); // John
alert(user.canView); // true
alert(user.canEdit); // true

If the copied property name already exists, it gets overwritten:

let user = {
  name: "John"
};
0

We also can use

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference
7 to perform a simple object cloning:

let user = {
  name: "John"
};
1

Here it copies all properties of

let user = { name: "John" };

let admin = user; // copy the reference
0 into the empty object and returns it.

There are also other methods of cloning an object, e.g. using the spread syntax

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference
9, covered later in the tutorial.

Until now we assumed that all properties of

let user = { name: "John" };

let admin = user; // copy the reference
0 are primitive. But properties can be references to other objects.

Like this:

let user = {
  name: "John"
};
2

Now it’s not enough to copy

let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
1, because
let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
2 is an object, and will be copied by reference, so
let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
3 and
let user = { name: "John" };

let admin = user; // copy the reference
0 will share the same sizes:

let user = {
  name: "John"
};
3

To fix that and make

let user = { name: "John" };

let admin = user; // copy the reference
0 and
let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
3 truly separate objects, we should use a cloning loop that examines each value of
let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
7 and, if it’s an object, then replicate its structure as well. That is called a “deep cloning” or “structured cloning”. There’s structuredClone method that implements deep cloning.

The call

let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
8 clones the
let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
9 with all nested properties.

Here’s how we can use it in our example:

let user = {
  name: "John"
};
4

The

let a = {};
let b = {}; // two independent objects

alert( a == b ); // false
0 method can clone most data types, such as objects, arrays, primitive values.

It also supports circular references, when an object property references the object itself (directly or via a chain or references).

For instance:

let user = {
  name: "John"
};
5

As you can see,

let a = {};
let b = {}; // two independent objects

alert( a == b ); // false
1 references the
let a = {};
let b = a; // copy the reference

alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
3, not the
let user = { name: "John" };

let admin = user; // copy the reference
0! So the circular reference was cloned correctly as well.

Although, there are cases when

let a = {};
let b = {}; // two independent objects

alert( a == b ); // false
0 fails.

For instance, when an object has a function property:

let user = {
  name: "John"
};
6

Function properties aren’t supported.

To handle such complex cases we may need to use a combination of cloning methods, write custom code or, to not reinvent the wheel, take an existing implementation, for instance from the JavaScript library lodash.

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.

All operations via copied references (like adding/removing properties) are performed on the same single object.

To make a “real copy” (a clone) we can use

let user = { name: 'John' };

let admin = user;

admin.name = 'Pete'; // changed by the "admin" reference

alert(user.name); // 'Pete', changes are seen from the "user" reference
7 for the so-called “shallow copy” (nested objects are copied by reference) or a “deep cloning” function
let a = {};
let b = {}; // two independent objects

alert( a == b ); // false
0 or use a custom cloning implementation, such as .

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

Object.assign() The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object.

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

assign(): By using the Object. assign() method, all enumerable properties of one or more source objects are copied to the target object. This method returns the modified target object. The properties of the target object are overwritten if they have the same key as properties in the sources.

How do I copy values from one object to another in JavaScript?

To copy an object in JavaScript, you have three options:.
Use the spread ( ... ) syntax..
Use the Object. assign() method..
Use the JSON. stringify() and JSON. parse() methods..

How to get specific property from object in JavaScript?

You can access the properties of an object in JavaScript in 3 ways:.
Dot property accessor: object. property..
Square brackets property accessor: object['property'].
Object destructuring: const { property } = object..