0

Im trying to understand how arrays work. I cannot seem to access certain keys in an array. the array is

const array = [
 {
  username: "john",
  team: "red",
  score: 5,
  items: ["ball", "book", "pen"]
 },
 {
  username: "becky",
  team: "blue",
  score: 10,
  items: ["tape", "backpack", "pen"]
 }];

I tried to console.log(array.username) and also (this.array.username) and all the array['username'] variations. But it always returns undefined (or returns "cannot read property username of undefined." But when i use "console.log (array[0].username)" it gives me the value.

so how can I access (or console.log) all the value of the "username" keys, without using an exact point like (array[0][1])?

Codebebe
  • 11
  • 5

1 Answers1

0

so how can I access (or console.log) all the value of the "username" keys, without using an exact point like (array[0])?

Use map

var allUserNames = array.map( s => s.username  ) 
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • thanks, but im trying to do it without any functions. just the data – Codebebe Mar 31 '18 at 08:43
  • 1
    @Codebebe *just the data* What does that mean? – gurvinder372 Mar 31 '18 at 08:44
  • I want to just console.log that data that is inside the array. in this case - the value of the "username" key. With objects i could just say - console.log(obj.username) But it doesnt work for the array. Either im doing something wrong, or one cannot access array data like access array like objects? – Codebebe Mar 31 '18 at 13:25
  • yes, since this is an array, you either will have to individually access those usernames by doing `array[0].username`, `array[1].username`, etc. or you need to iterate the array using **for-loop** or functions like `map` or `forEach`. – gurvinder372 Mar 31 '18 at 13:30