2

When I run this code I have a different result in the browser than in node

const users = [
  {
    id: 1,
    name: "ada",
    surname: "wong",
    games: [
      { id: 1, name: "g1" },
      { id: 2, name: "g2" },
    ],
  },
  {
    id: 2,
    name: "leon",
    surname: "kennedy",
    games: [{ id: 2, name: "g2" }],
  },
];

const output = users.map((user) => ({ ...user }));

console.log(output);

In the browser I can see the expected result

[
  {
    "id": 1,
    "name": "ada",
    "surname": "wong",
    "games": [
      {
        "id": 1,
        "name": "g1"
      },
      {
        "id": 2,
        "name": "g2"
      }
    ]
  },
  {
    "id": 2,
    "name": "leon",
    "surname": "kennedy",
    "games": [
      {
        "id": 2,
        "name": "g2"
      }
    ]
  }
]

But when I run it with node I get this result

$node app.js

ouput

[
  {
    id: 1,
    name: 'ada',
    surname: 'wong',
    games: [ [Object], [Object] ]
  },
  { id: 2, name: 'leon', surname: 'kennedy', games: [ [Object] ] }
]

I have tried to correct this behavior [ [Object], [Object] ] in node in the following ways, but after trying them all return the same result

const output = users.map((user) => ({ ...user, games: user.games }));
const output = users.map((user) => ({ ...user, games: [...user.games] }));
const output = users.map((user) => ({
  ...user,
  games: user.games.map(({ id, name }) => ({ id, name })),
}));

Why does destructuring objects within another object have a different output in the browser than in node? How to fix it in node?

Mario
  • 4,784
  • 3
  • 34
  • 50

2 Answers2

1

It's the same object, it's just presented differently. In your browser you can click through the object to dive into the details, and node will limit how deep it presents objects to not output too much.

Evert
  • 93,428
  • 18
  • 118
  • 189
1

It's about string and object on browser and terminal originally browser turn all thing to string or you can into objects on logs if you want deep log in nodejs you can use both ways

first way

// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });

second way

// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2)); 
H.Rafiee
  • 358
  • 1
  • 9
  • 1
    out of curiosity, where have you found the extra parameter for `console.dir()`? because in mdn https://developer.mozilla.org/en-US/docs/Web/API/Console/dir there is no reference to it – Mario Jun 26 '20 at 05:32
  • 3
    @Mario it's [Node's implementation](https://nodejs.org/api/console.html#console_console_dir_obj_options) – VLAZ Jun 26 '20 at 05:33
  • 1
    The answer has the same comments as [this answer](https://stackoverflow.com/a/48207620/3082296) from the duplicate. If taken from here, please add attribution. Or better, flag as duplicate from next time. – adiga Jun 26 '20 at 06:19