techdog
techdog

Reputation: 1481

How do I show console.log output in an alert

If I create an object and use console.log it will expand the object and I can see the object properties. If I use alert it does not. Is there any way to do the same thing in an alert?

    car=new Object();
    car.wheels=4;
    car.make="honda";
    car.owner="me"

    console.log(car); 

output: Object { wheels: 4, make: "honda", owner: "me" }

alert(car)

output is [object Object]

How can I get the same output for the alert?

Upvotes: 1

Views: 2280

Answers (3)

Intervalia
Intervalia

Reputation: 10945

As others have stated you use JSON.stringify.

But I wanted to give a few other pointers. I don't know if you know these already, but your example indicated that you might appreciate the tips.

  1. In JavaScript it is recommended to not use new Object() Instead just create your object:

var car = {
  wheels: 4,
  make: "honda",
  owner: "me"
}

  1. Always use var, let or const when creating variables. If you don't then they are created on the global scope. In the browser you would be creating the new variables on the window object.

  2. JSON.stringify has other parameters:

JSON.stringify(value[, replacer[, space]])

The replacer is not often used, but it can provide a way of filtering and preventing recursive data.

The space parameter can be a number form 0 to 10 or a number of characters in a string from 0 to 10. This indicates how much to indent each level in the output.

function replacer(key, value) {
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
}

var foo = {
  company: 'Sony',
  model: 'Playstation',
  version: 4, 
  pricing: [
    {
      pro: false,
      price: 299.00
    },
    {
      pro: true,
      price: 399.00
    }
  ],
  comments: 'none'
};
alert(JSON.stringify(foo, replacer, 2));
alert(JSON.stringify(foo, replacer, '----'));

Upvotes: 4

Prashanth
Prashanth

Reputation: 119

In the console log method, the parameter is considered as an object. So, the object can be in any form like an array, string, integer, etc., and We will get the content. But in the alert method, it accepts only the string. So, if you send the object, it will convert it as string version of the object ( object Object ). If you stringify the object and send as a parameter to the alert method, it will display the content. Try this one,

window.alert(JSON.stringify(object));

Upvotes: 1

Anas AL-zghoul
Anas AL-zghoul

Reputation: 467

You can use this alert(JSON.stringify(object))

Upvotes: 1

Related Questions