Search code examples
javascriptobject

How to display an object item


i want to try to display my object item in console with console.log but console shows it as undefined. Can you help me?

var myMusic = 
[
  {
    "artist": "Billy Joel",
    "title": "Piano Man",
    "release_year": 1973,
    "formats": [
      "CD",
      "8T",
      "LP"
    ],
    "gold": true
  },
  {
    "artist": "Beau Carnes",
    "title": "Cereal Man",
    "release_year": 2003,
    "formats": [
      "Youtube Video"
  ],
  },    
];

console.log(myMusic.artist);

I am tried that, and i was expected to see Billy Joel in console but it wrote undefined in console


Solution

  • This is a simple mistake, check comments in the codeblock, if i can help further, please comment

    var myMusic = 
    [
      {
        "artist": "Billy Joel",
        "title": "Piano Man",
        "release_year": 1973,
        "formats": [
          "CD",
          "8T",
          "LP"
        ],
        "gold": true
      },
      {
        "artist": "Beau Carnes",
        "title": "Cereal Man",
        "release_year": 2003,
        "formats": [
          "Youtube Video"
      ],
      },    
    ];
    
    console.log(myMusic.artist); // undefined because myMusic is an array
    console.log(myMusic[0].artist); // "Billy Joel"
    console.log(myMusic[1].artist); // "Beau Carnes"
    console.log(myMusic[0]) /* 
    {
        "artist": "Billy Joel",
        "title": "Piano Man",
        "release_year": 1973,
        "formats": [
          "CD",
          "8T",
          "LP"
        ],
        "gold": true
      } */