Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Using JSON.stringify() to display spread operator result?
The spread operator (...) allows you to expand objects and arrays into individual elements. When combining objects with the spread operator, you can use JSON.stringify() to display the merged result as a formatted string.
Syntax
// Object spread syntax
var result = { ...object1, ...object2 };
// Convert to JSON string
JSON.stringify(result);
Example
Here's how to use the spread operator to merge objects and display the result:
var details1 = { name: 'John', age: 21 };
var details2 = { countryName: 'US', subjectName: 'JavaScript' };
var result = { ...details1, ...details2 };
console.log("Merged object:");
console.log(JSON.stringify(result));
// Pretty-printed JSON with indentation
console.log("\nFormatted JSON:");
console.log(JSON.stringify(result, null, 2));
Output
Merged object:
{"name":"John","age":21,"countryName":"US","subjectName":"JavaScript"}
Formatted JSON:
{
"name": "John",
"age": 21,
"countryName": "US",
"subjectName": "JavaScript"
}
How It Works
The spread operator ... extracts all properties from each object and combines them into a new object. Properties from later objects override earlier ones if they have the same key. JSON.stringify() then converts the merged object into a JSON string representation.
Key Points
- The spread operator creates a shallow copy of object properties
-
JSON.stringify()converts the result to a readable string format - Use the third parameter of
JSON.stringify()for pretty-printed output - Later objects override properties with the same name from earlier objects
Conclusion
Using JSON.stringify() with spread operator results provides a clear way to visualize merged objects. The combination is particularly useful for debugging and logging object transformations.
