JavaScript Display Objects
Displaying a JavaScript object will output [object Object].
Example
const person = <
name: «John»,
age: 30,
city: «New York»
>;
- 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()
Displaying Object Properties
The properties of an object can be displayed as a string:
Example
const person = <
name: «John»,
age: 30,
city: «New York»
>;
document.getElementById(«demo»).innerHTML =
person.name + «,» + person.age + «,» + person.city;
Displaying the Object in a Loop
The properties of an object can be collected in a loop:
Example
const person = <
name: «John»,
age: 30,
city: «New York»
>;
let txt = «»;
for (let x in person) txt += person[x] + » «;
>;
You must use person[x] in the loop.
person.x will not work (Because x is a variable).
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
const person = <
name: «John»,
age: 30,
city: «New York»
>;
const myArray = Object.values(person);
document.getElementById(«demo»).innerHTML = myArray;
Object.values() is supported in all major browsers since 2016.
Using JSON.stringify()
Any JavaScript object can be stringified (converted to a string) with the JavaScript function JSON.stringify() :
const person = <
name: «John»,
age: 30,
city: «New York»
>;
let myString = JSON.stringify(person);
myString is now a JavaScript string, ready to be displayed:
Example
const person = <
name: «John»,
age: 30,
city: «New York»
>;
let myString = JSON.stringify(person);
document.getElementById(«demo»).innerHTML = myString;
The result will be a string following the JSON notation:
JSON.stringify() is included in JavaScript and supported in all major browsers.
Stringify Dates
JSON.stringify converts dates into strings:
Example
const person = <
name: «John»,
today: new Date()
>;
let myString = JSON.stringify(person);
document.getElementById(«demo»).innerHTML = myString;
Stringify Functions
JSON.stringify will not stringify functions:
Example
let myString = JSON.stringify(person);
document.getElementById(«demo»).innerHTML = myString;
This can be «fixed» if you convert the functions into strings before stringifying.
Example
const person = <
name: «John»,
age: function ()
>;
person.age = person.age.toString();
let myString = JSON.stringify(person);
document.getElementById(«demo»).innerHTML = myString;
Stringify Arrays
It is also possible to stringify JavaScript arrays:
Example
const arr = [«John», «Peter», «Sally», «Jane»];
let myString = JSON.stringify(arr);
document.getElementById(«demo»).innerHTML = myString;
The result will be a string following the JSON notation:
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to Display JavaScript Objects as HTML Elements
In this tutorial, you’ll learn how to display a list of JavaScript objects as a list of HTML elements on a web page.
Let’s say you have a list of JavaScript objects, and you need to output them as HTML elements in the web browser. In this example, we have a list of exercises, represented by a JavaScript object literal.
The JavaScript object literal:
let exerciseList = [ name: "Deadlift", >, name: "Push-up", >, name: "Pull-up", >, name: "Squat", >, ];
The above is a JavaScript object literal array with four objects (exercises). We want to take those objects and display them as a list in the browser, like this:
That’s an unordered list. If you inspect the list above in Chrome DevTools, the HTML markup for the list above will look like this:
ul> li>Deadliftli> li>Pull-upli> li>Push-upli> li>Squatli> ul>
Displaying the JavaScript object literal array as HTML elements
We need to take care of the following four steps:
- Create an empty unordered list element with HTML, so we can add our exercise list items inside it.
- Find and grab hold of all the exercises from the JavaScript object literal array, by using a for loop.
- Wrap each individual exercise object inside list item ( ) tags.
- Output the list item HTML elements in the browser inside the unordered list element ( ) that we created in step 1.
1. Create an empty unordered list element
To set up an empty unordered list element in HTML, add the following inside your index.html (or your HTML window if you use something like CodePen):
Now let’s assign a reference to that unordered list to a variable, so we can add it to our unordered list later. Add the following code at the top of your script file:
let exerciseList = document.querySelector(".exercise-list");
2. Loop through exercise objects
Since we’re dealing with individual exercise objects inside an array, we need to loop (iterate) through each exercise before we can do something with them.
Add the following code right below your JS object:
for (let exercise of exerciseList) console.log(exercise.name); >
Your entire script file should look like this now:
let exerciseList = document.querySelector(".exercise-list"); let exerciseObjects = [ name: "Deadlift", >, name: "Push-up", >, name: "Pull-up", >, name: "Squat", >, ]; for (exercise of exerciseObjects) console.log(exercise.name); >
Now check your browser console, and you should see this:
Now we have access to each individual exercise object.
3. Wrapping each exercise inside an HTML list item element
Now let’s wrap our collected exercise items inside the list item tag:
First, add the following variable right before your for loop begins:
Now inside your loop, add this:
Now if you console.log(exerciseItems) (outside and below your loop) your console will output each exercise item wrapped inside list item elements.
4. Add the exercise items inside the exercise list
Finally, to display our exercise items inside our exercise list element, add this code right below your for loop:
exerciseList.innerHTML = exerciseItems;
If you did everything correctly, your unordered exercise list should now display all exercises items inside your browser window.
Here’s all the code we wrote as a reference:
(function() let exerciseList = document.querySelector(".exercise-list"); let exerciseObjects = [ name: "Deadlift", >, name: "Push-up", >, name: "Pull-up", >, name: "Squat", >, ]; let exerciseItems = ""; for (exercise of exerciseObjects) exerciseItems += "<li>" + exercise.name + "</li>"; > exerciseList.innerHTML = exerciseItems; >)();
Here’s a CodePen with all the working code.
Has this been helpful to you?
You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊
Перебор массивов и объектов в JS
Сборник методов для перебора элементов массива или массивоподобных объектов.
Цикл for
Перебор массива в цикле for
var data = ["Яблоко", "Апельсин", "Слива"]; for (var key in data)
Результат:
Перебор объекта в цикле for
var data = ; for (var key in data)
Результат:
Цикл forEach
var data = ["Яблоко", "Апельсин", "Слива"]; data.forEach(function(element, key)< console.log(key + ': ' + element); >);
Результат:
Перебор объектов с помощью forEach
var data = ; Object.entries(data).forEach((entry) => < const Javascript show all objects = entry; console.log(key + ': ' + value); >);
Результат:
JQuery .each()
Метод .each() предназначен для цикличного обхода DOM-элементов, но также работает и массивами и объектами.
var data = ["Яблоко", "Апельсин", "Слива"]; $.each(data, function(key, value)< console.log(key + ': ' + value); >);
Результат:
Перебор объектов с помощью each()
var data = ; $.each(data, function(key, value)< console.log(key + ': ' + value); >);
Результат:
Комментарии
Другие публикации
Web Storage API это набор методов, при помощи которых в браузере можно хранить данные в виде пар ключ=значение на.
AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.
В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.
Сборник jQuery приемов с textarea — получить содержимое, вставить значение, подсчет количества символов и строк и т.д.
Для замены Favicon во вкладке браузера достаточно у элемента link rel=»icon» в атрибуте href указать путь до нового.