SoFunction
Updated on 2025-04-10

3 ways to add objects to objects in JS

Front-end development: Methods for adding objects to objects in JS

There are about three ways to add objects to objects in JS: directly add and use extension operators...

()method.

1. Add directly

Directly add the required key-value pair content to object A, the specific example is as follows:

let objectA = {
	  name: 'Tom'
	};
	let key = 'age';
	let value = 31;
	objectA[key] = value;   //The result is: = 18	( 'objectA===>',objectA);  //The output result is:objectA===> {name: 'Tom', age: 31}

2. Use the extension operator...

Using the extension operator... It is a common way to add objects to objects. The specific examples are as follows:

	let objectA = {
	    name: 'Tom'
	};   
	
	let objectB = {
	     age: 31   
	};
	
	let object = { ...objectA, ...objectB};
	
	( 'object===>',object);   //The output result is:object===> {name: 'Tom', age: 31}

3. () method

The () method has several uses, mainly used to copy the values ​​of all enumerable attributes from one or more source objects into the target object. Here we mainly introduce the functions related to object merging, and the specific examples are as follows:

let objectA = {
	    name: 'Tom'
	};   
	let objectB = {
	    age: 31   
	};
	( objectA, objectB);
	( 'objectA===>',objectA);  //The output result is:objectA===> {name: 'Tom', age: 31}

Summarize

This is the article about 3 ways to add objects to objects in JS. This is all about this. For more related JS objects, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!