Loading Please Wait...
When we try to display object by it's variable name, it will show [object Object].
const user = { name: "John", city: "New York" };
alert(user); // [object Object]
We can display objects by the following ways:
The properties of an object can be displayed as a string.
const user = { name: "John", city: "New York" };
alert(user.name); // "John"
The properties of an object can be collected in a loop.
const user = { name: "John", city: "New York" };
let text = "";
for (let prop in user) {
text += user[prop] + " ";
};
alert(text); // "John New York"
You must use person[x] in the loop. person.x will not work (Because x is a variable).
Any JavaScript object can be converted to an array using Object.values()
const user = { name: "John", city: "New York" };
const myArray = Object.values(user);
alert(myArray); // "John,New York"
Any JavaScript object can be stringified (converted to a string) with the JavaScript function JSON.stringify().
const user = { name: "John", city: "New York" };
alert(JSON.stringify(user)); // "{"name":"John","city":"New York"}"
JSON.stringify converts dates into strings.
const user = { name: "John", today: new Date() };
alert(JSON.stringify(user)); // "{"name":"John","today":"2023-07-28T12:35:24.317Z"}"
JSON.stringify will not stringify functions. This can be "fixed" if you convert the functions into strings before stringifying.
const user = {
name: "John",
age: function () {return 30;}
};
alert(JSON.stringify(user)); // "{"name":"John"}"
user.age = user.age.toString();
alert(JSON.stringify(user)); // "{"name":"John","age":"function () {return 30;}"}"
It is also possible to stringify JavaScript arrays.
const arr = ["John", "Peter", "Sally", "Jane"];
alert(JSON.stringify(arr)); // "["John","Peter","Sally","Jane"]"
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved