Append Values to Object in JavaScript

  1. Use the object.assign() Method to Append Elements to Objects in JavaScript
  2. Use the push() Method to Append Elements to Objects in JavaScript
  3. Use the Spread Operator to Append to Objects in JavaScript

Objects are mutable by default in JavaScript. We can modify them afterward, depending on our requirements.

This tutorial demonstrates how to append values to JavaScript objects.

Use the object.assign() Method to Append Elements to Objects in JavaScript

The object.assign() method will copy all properties defined in an object to another object, i.e., it copies all properties from one or more sources to the target objects. By doing this, we are appending an element to the object.

For example,

const course = {
  name: 'JavaScript'  
};
const grade = {
  score: 92  
};
const finalResult = Object.assign(course,grade);
console.log(finalResult);

Output:

{ name: 'JavaScript', score: 92 }

Use the push() Method to Append Elements to Objects in JavaScript

The push() function adds single or multiple elements to the end of an array and returns the new length of the array.

For example,

const brands = ['nike', 'reebok', 'adidas'];
const count = brands.push('venum');
console.log(count);
console.log(brands);

Output:

4
[ 'nike', 'reebok', 'adidas', 'venum' ]

Note that count returns the length of the array. This is probably the most straightforward method to append elements to an object enclosed in an array. It is advisable to use arrays since they are also mutable.

For example,

const brands = [{nike:1500}];
const count = brands.push({reebok:2000});
console.log(count);
console.log(brands);

Output:

2
[{nike: 1500},{reebok: 2000}]

Use the Spread Operator to Append to Objects in JavaScript

The spread operator is used to merge or clone objects in JavaScript. It can be used when all elements in an object need to be included in some list.

For example,

const rectangle = {
    radius: 10
};
const style = {
    Backcolour: 'red'
};
const solidRectangle = {
    ...rectangle,
    ...style
};
console.log(solidRectangle);

Output:

{ radius: 10, Backcolour: 'red' }
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Object

  • Deep Clone an Object in JavaScript
  • Merge Objects in Javasript