I’m playing with a netflix dataset in p5.js and am having issues viewing individual elements (purely for debugging purposes, for now).
E.g I’m trying to view element 0 in the array/object(?) but it always returns undefined.
For example, if I console.log the array/object itself, I can see entries:
console.log(myArray) {Brazil: 1, Mexico: 2, Singapore: 1, United States: 13, Turkey: 4, …} "": 2 Brazil: 1 Canada: 2 Egypt: 1 Iceland: 1 India: 7 Indonesia: 2 Italy: 1 Japan: 1 Mexico: 2 Nigeria: 2 Norway, Iceland, United States: 1 Poland, United States: 1 Romania: 2 Singapore: 1 South Africa, Nigeria: 1 South Korea: 1 Spain: 1 Thailand: 1 Turkey: 4 United Kingdom: 1 United States: 13
However, if I try and print [0] for my array, it shows as undefined
console.log(myArray[0]) results in: 201 <code>.js:158 undefined
But if I try what I usually would with a multidimensional array, I see the following, which implies my type is off, but typeOf only shows it as an ‘object’
Uncaught TypeError: Cannot read property '0' of undefined
This seems to imply that this isn’t an array at all. What is it?
Any help or guidance is appreciated. Thanks!
For reference, this is how the object was originally created (full 8000~ dataset was condensed via this method: https://www.tutorialspoint.com/counting-unique-elements-in-an-array-in-javascript
Advertisement
Answer
myArray
is an object. For an object myArray[0]
doesn’t work. Fetching an element with index only works for Array.
You can use the below code to loop over all the key-values.
const myArray = { "Brazil": 1, "Mexico": 2, "Singapore": 1, "United States": 13, "Turkey": 4 }; for (const property in myArray) { console.log(`${property}: ${myArray[property]}`); }
If you want the list of keys then you can use Object.keys
let myObj ={"Brazil": 1, "Mexico": 2, "Singapore": 1, "United States": 13, "Turkey": 4} console.log(Object.keys(myObj));
And if you want the list of values then you can use Object.values
let myObj ={"Brazil": 1, "Mexico": 2, "Singapore": 1, "United States": 13, "Turkey": 4} console.log(Object.values(myObj));