➥ JS Tutorial
- JS HOME
- JS introduction
- JS Where to
- JS Output
- JS Statements
- JS Syntax
- JS Variables
- JS Operators
- JS Assignment
- JS Data Types
- JS Functions
- JS Objects
- JS Events
- JS Sting methods
- JS String Search
- JS Arrays Methods
- JS Arrays
- JS Sorting Arrays
- JS Array Iteration
- JS Math Object
- JS Comparison & Logical Operators
- JS if else and else if
- JS Switch Statement
- JS For Loop
- JS For In
- JS For Of
- JS While Loop
- JavaScript Break
- JS Sets
- JavaScript typeof
- JS Type Conversion
- JS Bitwise Operations
- JS JSON
- JS Best Practices
- JS Reserved Words
- JS Number Methods
➥ JS Objects
➥ JS Functions
➥ JS Classes
➥ JS HTML DOM
- JavaScript HTML DOM
- JS HTML DOM Document
- JS HTML DOM Elements
- Changing HTML
- JS Forms
- JS HTML DOM - CSS
- DOM Events
- HTML DOM Event Listener
➥ JS Browser BOM
➥ JS Web APIs
➥ JS AJAX
➥ JS JSON
Tutorial
How to Display JavaScript Objects?
Displaying a JavaScript object will output [object Object].
Some common solutions to display JavaScript objects are:
• Displaying the Object Properties by name
• Displaying the Object Properties in a Loop
• Displaying the Object using Object.values()
• Displaying the Object using JSON.stringify()
EXAMPLE ❯
Displaying Object Properties
The properties of an object can be displayed as a string:
EXAMPLE ❯
Displaying the Object in a Loop
The properties of an object can be collected in a loop:
You must use person[x] in the loop.
person.x will not work (Because x is a variable).
EXAMPLE ❯
Using Object.values()
Any JavaScript object can be converted to an array using Object.values():
const person = {
name: "John",
age: 30,
city: "New York"
};
const myArray = Object.values(person);
myArray
is now a JavaScript array, ready to be displayed:
EXAMPLE ❯
Using JSON.stringify()
Any JavaScript object can be stringified (converted to a string) with the JavaScript function JSON.stringify()
JSON.stringify() is included in JavaScript and supported in all major browsers.
EXAMPLE ❯
Stringify Dates
JSON.stringify converts dates into strings:
EXAMPLE ❯
Stringify Functions
JSON.stringify will not stringify functions:
Example:
<script>
const person = {
name: "John",
age: function () {return 30;}
};
document.getElementById("demo").innerHTML = JSON.stringify(person);
</script>
In above example, It does not returns age,
Output:
{"name":"John"}
This can be "fixed" if you convert the functions into strings before stringifying.
EXAMPLE ❯
Stringify Arrays
It is also possible to stringify JavaScript arrays:
Following code's result will be a string following the JSON notation:
["John","Peter","Sally","Jane"]