Needing Help with Manipulating Complex Objects

How do I output the value “Daft Punk” or “CD” using function? I don’t know where I should add JSON.stringify( ) to output the value.

var ourMusic = [
 {
 "artist": "Daft Punk",
 "title": "Homework",
 "release_year": 1997,
 "formats": ["CD", "Cassette", "LP"
 ],
 "gold": true
 }
];

function myFunc(val){
    if(ourMusic.hasOwnProperty(val) == true){
      return ourMusic[val];
  }else{
        return "Not Found";
   }
}

var result = myFunc('artist');
document.write(result);

Greetings @MizoCoder,

You may want to remove the “” wrapping the object’s names, as well as removing the brackets surrounding the variable, as it isn’t an array by itself.

var ourMusic = {
 artist: "Daft Punk",
 title: "Homework",
 release_year: 1997,
 formats: ["CD", "Cassette", "LP"],
 gold: true
}

function myFunc(val){
    
    if(ourMusic.hasOwnProperty(val) == true){
      return (ourMusic[val]);
  }else{
        return "Not Found";
   }
}

var result = myFunc("artist");
document.write(result);

This results in “Daft Punk” being written in the document.

Without the brackets it works perfectly fine but this is an array which contains one object inside. I just wanted to know if it is possible to output the value; the lesson only gives an example and doesn’t explain much. My understanding is “artist”: “Daft Punk”, is the same as artist: “Daft Punk”,

var ourMusic = [
 {
 "artist": "Daft Punk",
 "title": "Homework",
 "release_year": 1997,
 "formats": [
 "CD",
 "Cassette",
 "LP"
 ],
 "gold": true
 }
];

Hey @MizoCoder,

This may be what you’re looking for!

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

function myFunc(val){
    if(myMusic[0].hasOwnProperty(val) == true){
      return myMusic[0][val];
  } else {
        return "Not Found";
   }
}

var result = myFunc("artist");

console.log(result);

This way, you’re looking for a property on myMusic’s array at index 0, and returning the value found inside that property. This prints the artist name on console.

1 Like

Yes, exactly. If I want to output just the “CD” or “8T” how do I change the index?