我有这个嵌套数组。
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"]
}
];
我知道如何访问像这样的数组中的属性:
contacts[0][firstName]
获得"Akira"
。但是我想显示嵌套数组中的第一个数组。我该怎么做呢?如果我只输入console.log(contacts[0]);
,我会得到[object Object]
。
我听说过JSON.parse()。是在嵌套数组或任何其他数组中显示第一个数组的正确方法吗?
答案 0 :(得分:1)
我认为您需要一个JSON.stringify()
而不是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, ' '));
答案 1 :(得分:1)
如果在您的数据结构上,likes
始终是数组,则可以通过以下方式访问它:
contacts[0].likes
控制台记录它:
console.log(contacts[0].likes)
。
您还可以通过遍历对象来访问每个数组:
contacts.forEach(contact => {
console.log(contact.likes)
})