Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Objects Display

JavaScript display objects refer to elements in the DOM used for rendering webpage content, manipulated dynamically via JavaScript for interactive user experiences.

How to Display JavaScript Objects?

When displaying a JavaScript object, the output will show as [object Object].

Example

// Create an Object
const person = {
  name: “John”,
  age: 30,
  city: “New York”
};

document.getElementById(“demo”).innerHTML = person;

Here are several methods to present JavaScript objects:

  • Displaying object properties individually by name
  • Iterating through object properties in a loop
  • Using Object.values() to list object values
  • Using JSON.stringify() to output the object

Displaying Object Properties

The properties of an object can be displayed as a string.

Example

// Create an Object
const person = {
  name: “John”,
  age: 30,
  city: “New York”
};

// Display Properties
document.getElementById(“demo”).innerHTML =
person.name + “,” + person.age + “,” + person.city;

Displaying Properties in a Loop

The properties of an object can be gathered in a loop.

Example

// Create an Object
const person = {
  name: “John”,
  age: 30,
  city: “New York”
};

// Build a Text
let text = “”;
for (let x in person) {
  text += person[x] + ” “;
};

// Display the Text
document.getElementById(“demo”).innerHTML = text;

Note:

You must use person[x] in the loop.

 

person.x will not work because x is the loop variable.

Using Object.values()

Object.values() generates an array from the property values.

// Create an Object
const person = {
  name: “John”,
  age: 30,
  city: “New York”
};

// Create an Array
const myArray = Object.values(person);

// Display the Array
document.getElementById(“demo”).innerHTML = myArray;

Using Object.entries()

Object.entries() simplifies using objects in loops.

Example

const fruits = {Bananas:300, Oranges:200, Apples:500};

let text = “”;
for (let [fruit, value] of Object.entries(fruits)) {
  text += fruit + “: “ + value + “<br>”;
}

Using JSON.stringify()

JavaScript objects can be converted to a string using the JSON.stringify() method.

JSON.stringify() is built into JavaScript and supported by all major browsers.

Note:

The output will be a string in JSON notation:

 

{"name":"John","age":50,"city":"New York"}

Example

// Create an Object
const person = {
  name: “John”,
  age: 30,
  city: “New York”
};

// Stringify Object
let myString = JSON.stringify(person);

// Display String
document.getElementById(“demo”).innerHTML = myString;