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?
2 Answers 2
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, ' '));
Comments
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)
})
Comments
Explore related questions
See similar questions with these tags.
JSON.parse. Different browsers will show different output forconsole.log(the link shows how to 'log objects' as well), so considerconsole.dirfor diagnostic display of objects instead.