-1

I cannot seem to get into an array that I'm needing to get into, in my console it appears as [] but you can expand it and it has more inside of it which I need access to.

I've tried using dot notation and bracket notation to get into the array but with no luck

This is part of my code:

console.log(gameData);
    _.each(gameData['1'], (games) => {
      console.log(games);
}

This is the array as it first appears in the console:

[]

This is the array expanded in the console:

0: "Games fetched successfully"
1: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
length: 2

I cannot access the array with gameData[1] which is what I need. Can you think of a reason why this is happening? I'm probably doing something simple wrong.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Chameleon
  • 119
  • 1
  • 14
  • I think `var data = gameData[1]` made the trick for you. Because array is an index based and index always be an integer. – er-sho Oct 29 '19 at 01:35
  • "*This is the array as it first appears in the console: `[]`*" - that's giving away the reason: when you try to access the data, the array *is* (still) empty – Bergi Oct 29 '19 at 01:51

1 Answers1

0

Assuming that gameData is an Array, you can access its items using this:

_.each(gameData, game => console.log(game));

You also don't really need _ here. You can simply use the forEach method on it:

gameData.forEach(game => console.log(game));

And yeah, since this is an Array which are 0 based, you can access it's elements using

gameData[index]

where index would be an integer(0, 1, 2) etc.

Here, give this a try:

const gameData = [{
    id: 1,
    name: 'Game 1'
  },
  {
    id: 2,
    name: 'Game 2'
  },
  {
    id: 3,
    name: 'Game 3'
  },
  {
    id: 4,
    name: 'Game 4'
  },
  {
    id: 5,
    name: 'Game 5'
  },
];

gameData.forEach(game => console.log(game));

console.log('Got the game at the 0th index as: ', gameData[0]);
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • gameData.forEach doesn't work and neither does the orginal _.each – Chameleon Oct 29 '19 at 00:55
  • Like I mentioned, I'm assuming that `gameData` is an Array. You might want to try and run the above code snippet and see the results. – SiddAjmera Oct 29 '19 at 00:57
  • Yours will work, I can tell by looking at it, however mine does not. it console logs as [] and you can expand it to see what I have above but I cannot drill down into it in my code for some reason. – Chameleon Oct 29 '19 at 01:00
  • It's not quite clear what you're facing. Would you mind creating a minimal verifiable stackblitz sample replicating the issue? – SiddAjmera Oct 29 '19 at 01:02
  • That will be hard as it's coming from the database unfortunately – Chameleon Oct 29 '19 at 01:04
  • You can mock the data and do it. Or atleast share the code that gets this data from the API and how you're logging the data that you're getting to the console? – SiddAjmera Oct 29 '19 at 01:05