kathrynm kathrynm - 3 months ago 20
Javascript Question

Object Content returning [object Object]

Trying to get content from my array of objects.

var array = [

first = {
'name': 'first',
'color': 'red',
},

second = {
'name': 'second',
'color': 'green',
},

third = {
'name': 'third',
'color': 'blue',
},
];

$('.first').text(first);
$('.second').text(second);
$('.third').text(third);


But instead it returns:

[object Object]


Can't seem to find an answer for this anywhere, am I missing something obvious?

codepen demo

Thanks in advance, :)


  • K


Answer

You are calling on JSON objects. You can grab the content within the objects using dot notation like:

Codepen - dot notation

$('.first').text(first.name + first.color);
$('.second').text(second.name + second.color);
$('.third').text(third.name + third.color);

If you really want to print out the object though, you can use JSON.stringify() like:

Codepen - JSON.Stringify()

$('.first').text(JSON.stringify(first));
$('.second').text(JSON.stringify(second));
$('.third').text(JSON.stringify(third));