0

I have this nested arrays.

var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["JavaScript", "Gaming", "Foxes"]
    }
];

I know how to access a property within an array like this:

contacts[0][firstName]

to get "Akira". But I wanted to display the first array within the nested arrays. How do I do this? If I just type in console.log(contacts[0]); I get [object Object].

I heard about JSON.parse(). Is it the correct way to display the first array within the nested arrays or any other array too?

Kristina Bressler
  • 1,642
  • 1
  • 25
  • 60
  • No, I wanted to see in console the first array – Kristina Bressler Jul 01 '19 at 20:45
  • There is no JSON there, so no need for `JSON.parse`. *Different browsers will show different output for [`console.log`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log)* (the link shows how to 'log objects' as well), so *consider [`console.dir`](https://developer.mozilla.org/en-US/docs/Web/API/Console/dir) for diagnostic display of objects* instead. – user2864740 Jul 01 '19 at 20:45
  • Possible duplicate of [How to print object array in JavaScript?](https://stackoverflow.com/questions/14895287/how-to-print-object-array-in-javascript) – Bosco Jul 01 '19 at 20:53

2 Answers2

1

I think you need a JSON.stringify() instead of JSON.parse().

var contacts = [{
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
  },
  {
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
  },
  {
    "firstName": "Sherlock",
    "lastName": "Holmes",
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
  },
  {
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["JavaScript", "Gaming", "Foxes"]
  }
];

console.log(JSON.stringify(contacts[0], null, '  '));
zmag
  • 7,825
  • 12
  • 32
  • 42
1

If, on your data structure, likes is always an array, you can access it this way: contacts[0].likes

console logging it: console.log(contacts[0].likes).

You can also access every array by looping through the object:

contacts.forEach(contact => {
  console.log(contact.likes)
})
Marcelo Cardoso
  • 251
  • 3
  • 10