0

I am digging into some JavaScript at the moment and I have a given function from which I want to return an object similar to HashMap. Here are the contents of the function:

function(video){
    var obj = {"title":video.title, "id":video.id};
    console.log(obj);
    return obj;
}

The problem is that the console.log prints the correct values, but the return does not return them. Here is an example output:

console.log:

{title: "Die Hard", id: 2}
{title: "Avatar", id: 3}

return:

{[Object]}
{[Object]}
Svetoslav Petrov
  • 1,036
  • 1
  • 11
  • 33
  • Have you tried a console.log with the returned value? I am pretty sure it is OK. – Mario Dec 17 '14 at 12:21
  • When I tried console.log for the returned object, it showed correct output – Pramod Karandikar Dec 17 '14 at 12:22
  • In addition to answer below, instead of alerts or adding html to get a better look at an obj, you can pretty print too: `console.log(JSON.stringify(obj, null, 4))` – Todd Dec 17 '14 at 12:27

1 Answers1

1

I suspect you are alerting the results to the screen.

function video(){
  return {title: "Die Hard", id: 2}
}

a = video();

console.log(a); // Object {title: "Die Hard", id: 2}
alert(a); // [object Object]

You can read up on why that is, as well as possible solutions here: Print content of JavaScript object?

However, the bottom line is: just use console.log() to inspect objects (and anything else really).

Community
  • 1
  • 1
James Hibbard
  • 16,490
  • 14
  • 62
  • 74
  • Nope, I just map the object to another variable and use console.log() to print it. – Svetoslav Petrov Dec 17 '14 at 12:26
  • Can you make a fiddle demonstrating the problem? – James Hibbard Dec 17 '14 at 12:27
  • That works as expected for me. `videoIdAndBookmarkIdPairs` returns an array of objects. Initially this looks like `[Object, Object]` on the console, but if you click the triangle of the left of it, you can unfold it and explore the array's contents. If you want to see everything contained in the array in one go, @Todd's tip is a good one. `console.log(JSON.stringify(videoIdAndBookmarkIdPairs, undefined, 2));` will format the contents of the array nicely. – James Hibbard Dec 17 '14 at 12:38
  • Yes, stringify showed me the information in the objects, cheers! – Svetoslav Petrov Dec 17 '14 at 12:41
  • No probs. If that helped, maybe you could accept the answer. – James Hibbard Dec 17 '14 at 12:42