Javascript Add to Object: Insert Key/Value in JavaScript Object

An object in JavaScript is a collection of related data and/or functionality that normally consists of numerous variables and functions which are called properties and methods when they are inside objects. You can add or remove properties from the Object or copy the object.

Javascript Add to Object

To add properties or insert key-value pair in JavaScript Object, use either dot(.) notation or square bracket notation([ ]).

To create an Object in JavaScript, use the { } notation and add the key/value pairs to that Object.

const mama = {
 name: "PrafulChandra Rupani",
 age: 73
}

console.log(mama)
console.log("After adding a new property using . notation")

mama.Hobby = "Watching Cricket and News"

console.log(mama)

Output

{ name: 'PrafulChandra Rupani', age: 73 }

After adding a new property using . notation

{
 name: 'PrafulChandra Rupani',
 age: 73,
 Hobby: 'Watching Cricket and News'
}

In this example, we have created a JavaScript Object using curly braces({ }) and then add one more property using the dot notation.

Using square bracket notation

The square bracket notation is used when the name of the property is dynamically determined. 

let get_property = function (property_name) {
 return obj[property_name]
};

get_property("key1")
get_property("key2")
get_property("key3")

If we apply the bracket notation in our previous example, then it looks like below.

const mama = {
 name: "PrafulChandra Rupani",
 age: 73
}

console.log(mama)
console.log("After adding a new property using square bracket notation")

mama["Hobby"] = "Watching Cricket and News"

console.log(mama)

Output

{ name: 'PrafulChandra Rupani', age: 73 }

After adding a new property using square bracket notation

{
 name: 'PrafulChandra Rupani',
 age: 73,
 Hobby: 'Watching Cricket and News'
}

And we get the same output.

Object.assign()

The Object.assign() is a built-in JavaScript method used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

const x = { a: 11, b: 21 }
const y = { b: 46, c: 19 }

const returnedY = Object.assign(x, y)

console.log(x)

console.log(returnedY)

Output

{ a: 11, b: 46, c: 19 }
{ a: 11, b: 46, c: 19 }

That’s it for JavaScript add to object tutorial.

Leave a Comment