How to Add an Element to object JavaScript

In this tutorial, we will see how to add an element to a JavaScript object.

JavaScript object is a container that contained properties and methods. We can add properties to an empty object or an existing object.

How to Add an Element to object JavaScript

Add an Element to an existing object

Let’s take an example first. Suppose we have an object user that has some properties i.e. id, name, and age like below.

const user = {
	id:5,
	name:"John",
	age:35
};

Now if you want to add new property i.e. address. So how to do that?

const user = {
	id:5,
	name:"John",
	age:35
};

user.address = "NY";

console.log(user.address);

You can also add elements to an object by adding the key and value like this user['address'] = "NY";

Add Element to an empty object

You can create an object by object literal i.e. curly braces {} or by using new keyword i.e. const user = new Object(); After that add new elements or property to it.

const user = {};

user.id = 5;
user.name = "John";
user.age = 35;
user.address = "NY";

console.log(user.id + " " + user.name + " " + user.address);

Output:

5 John NY

Append element to object using Object.assign()

The Object.assign() method will copy all properties from source to target object. Let’s take an example first.

const user = {
	id:5,
	name:"John"
};

const newUser = Object.assign(user, {age: 35, address : "NY"} );
console.log(newUser);

Output:

{id: 5, name: "John", age: 35, address: "NY"}

Append element to object using spread operator

By using the spread operator, you can also combine two or more objects into a new object.

const user = {
	id:5,
	name:"John"
};

const user_address = {
	mob: 12345678,
	email: "[email protected]"
}

let newUser = {...user, ...user_address, ...{address : "NY"} };
console.log(newUser);

Output:

{id: 5, name: "John", mob: 12345678, email: "[email protected]", address: "NY"}

JavaScript object is mutable. That means after creating an object you can change its state. Let’s check an example.

const user = {
	id:5,
	name:"John"
};

const newUser = user;
newUser.address = "NY"
newUser.id = 2;

console.log(newUser);
console.log(user);

Output:

{id: 2, name: "John", address: "NY"}
{id: 2, name: "John", address: "NY"}

You can see in the above example where the output is the same. That means the user and newUser are the same objects. The object newUser is not a copy of the user.

Conclusion

I think the above methods will help you to add an element to a JavaScript object. That’s all for today’s tutorial. You can also learn something new in JavaScript from our JavaScript Tutorial. If you have any questions please comments below.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment