How do I display an Object type variable on the screen through Alert?

Asked

Viewed 39 times

2

In Alert the following message appears: [Object Object]

Follows code below:

let carro = {
    modelo: "corsa",
    marca: "chevrolet",
    aVenda: true
};

alert(carro);

2 answers

3

To show the object structure as text, you can use the function JSON.stringify, follows an example below:

let carro = {
    modelo: "corsa",
    marca: "chevrolet",
    aVenda: true
};

alert(JSON.stringify(carro));

Otherwise Alert shows only the type of the variable, which in this case is an Object. What the JSON.stringify does in this case is deserialize the object to a string containing the properties and values of the object.

3

According to the documentation, the method Window.alert has an argument message, that:

message is an optional string with the text you want to display in the dialog box, or an object to be converted into a string and displayed.

Thus, when you provide something that is not a string for this argument, the method will use the method toString of the value passed to try to represent it in textual format.

Thus, given that, by default, the method toString of an object (inherited, through the prototype chain, of the builder Object), returns [object Object], you cannot use this implicit conversion.

An option, as suggested by Marcell Alves in the other answer, is to use the method JSON.stringify, which serializes a Javascript object for its representation in JSON format (which is basically a string):

const carro = {
  modelo: "corsa",
  marca: "chevrolet",
  aVenda: true
};

alert(JSON.stringify(carro));

Another option is to override the method toString of the object, so that the implicit conversion is done according to a pre-defined format by you:

const carro = {
  modelo: "Corsa",
  marca: "Chevrolet",
  aVenda: true,
  
  // Sobrescrita do método `toString`:
  toString() {
    return `Carro ${this.modelo} ${this.marca}.` + (this.aVenda ? ' À venda' : '');
  }
};

alert(carro);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.