I have tried using console.log
so I can see the content of my array that contains multiple objects. However I get an error saying console.log
is not an object etc. I'm using jquery 1.6.2 and my array is like this:
filters = {dvals:[{'brand':'1', 'count':'1'},
{'brand':'2', 'count':'2'},
{'brand':'3', 'count':'3'}]}
console.log(filters);
What I want to to do is write out the contents of array(filters)
to an alert box (that's what I thought console.log
did) in the filters format. How do I do that?
there are two potential simple solutions to dumping an array as string. Depending on the environment you're using:
…with modern browsers use JSON:
JSON.stringify(filters);
// returns this
"{"dvals":[{"brand":"1","count":"1"},{"brand":"2","count":"2"},{"brand":"3","count":"3"}]}"
…with something like node.js you can use console.info()
console.info(filters);
// will output:
{ dvals:
[ { brand: '1', count: '1' },
{ brand: '2', count: '2' },
{ brand: '3', count: '3' } ] }
Edit:
JSON.stringify comes with two more optional parameters. The third "spaces" parameter enables pretty printing:
JSON.stringify(
obj, // the object to stringify
replacer, // a function or array transforming the result
spaces // prettyprint indentation spaces
)
example:
JSON.stringify(filters, null, " ");
// returns this
"{
"dvals": [
{
"brand": "1",
"count": "1"
},
{
"brand": "2",
"count": "2"
},
{
"brand": "3",
"count": "3"
}
]
}"