Reputation: 296
Basically, I'm wanting to output the rating of these guitars but I get a "TypeError: taylorGuitar.guitarRating is not a function. Here's the code:
var taylorGuitar = [
{
"model": "814ce",
"stringsCount": 6,
"pickup": true,
"stringsTuning": ["E", "A", "D", "G", "B", "E"],
"playabilityRating": 8,
"soundRating": 10,
"lookRating": 10,
"woods": {
"front": "Cedar",
"back": "Rosewood",
"fretboard": "Rosewood"
}
},
{
"model": "410ce",
"stringsCount": 6,
"pickup": true,
"stringsTuning": ["E", "A", "D", "G", "B", "E"],
"playabilityRating": 8,
"soundRating": 9,
"lookRating": 8,
"woods": {
"front": "Cedar",
"back": "Rosewood",
"fretboard": "Rosewood"
}
},
{
"guitarRating": function(){
totalScore = taylorGuitar.playabilityRating + taylorGuitar.soundRating + taylorGuitar.lookRating;
return totalScore;
}
}
];
var rating = taylorGuitar.guitarRating();
console.log(rating);
Upvotes: 1
Views: 66
Reputation: 3635
taylorGuitar.guitarRating is not a function nor is it defined actually.
taylorGuitar is an array that has three objects in your case:
[{/*omitted stuff for object 1 */}, {/*omitted stuff for object 2 */}, {/*omitted stuff for object 3 */}].
var object3 = taylorGuitar[2];
//object 3 now is the one:
{
"guitarRating": function(){
totalScore = taylorGuitar.playabilityRating + taylorGuitar.soundRating + taylorGuitar.lookRating;
return totalScore;
}
}
The last object is the object that contains 'guitarRating'
So just like @elclanrs said, taylorGuitar[2].guitarRating
this is the function that you can invoke using ().
Upvotes: 0
Reputation: 11188
Your object taylorGuitar is an array so you would need to include which element you want like so:
taylorGuitar[0].model;
You have also defined your function as part of that array which will make it difficult to access, your taylorGuitar object needs to have two elements, your array and the function:
taylorGuitar.dataArray = [...]
taylorGuitar.guitarRating = function() {...}
Then you need to change your function so that it loops through all items in the array.
EDIT:
I have rewritten your code so that it now works and added comments at the critical points:
var taylorGuitar = {"data": [
{
"model": "814ce",
"stringsCount": 6,
"pickup": true,
"stringsTuning": ["E", "A", "D", "G", "B", "E"],
"playabilityRating": 8,
"soundRating": 10,
"lookRating": 10,
"woods":
{
"front": "Cedar",
"back": "Rosewood",
"fretboard": "Rosewood"
}
},
{
"model": "410ce",
"stringsCount": 6,
"pickup": true,
"stringsTuning": ["E", "A", "D", "G", "B", "E"],
"playabilityRating": 8,
"soundRating": 9,
"lookRating": 8,
"woods":
{
"front": "Cedar",
"back": "Rosewood",
"fretboard": "Rosewood"
}
}], //note array ends
"guitarRating": function()
{
totalScore = 0;
//note you need to loop through the data
for(i=0;i<this.data.length;i++)
{
d = this.data[i];
totalScore += d.playabilityRating + d.soundRating + d.lookRating;
}
return totalScore;
}
};
var rating = taylorGuitar.guitarRating();
console.log(rating);
Upvotes: 1