I cant get multiple data from objects in arrays in javascript.
let superStars =[{
"name" : "Brock",
"age" : 38,
"type" : "wwe",
matchData :[
{played:10,
win:9,
lose:1,
available:"YES"}
],
"name" : "mike",
"age" : 40,
"type" : "boxer",
matchData : [
{played : 5,
win:3,
lose:2,
available:"NO"}
],
starsData : function(){
this.matchData.forEach((stardata)=>{
console.log(stardata);
});
}
}];
superStars.starsData();
i want both user ‘matchData’ data.
Error shown : Uncaught TypeError: superStars.starsData is not a function
2
Answers
superstars
is an array. And the functionstarsData
is stored on an element in that array. So you have to access that element first.Therefore:
superstars[0].starsData()
. The[0]
accesses the first element in the array (we start counting at 0). Also, put all matches in the same array instead of making two arrays. Meaning you only needmatchData
once, as shown above.let superStars = [
{
"name": "Brock",
"age": 38,
"type": "wwe",
"matchData": [
{ "played": 10, "win": 9, "lose": 1, "available": "YES" }
],
"starsData": function() {
this.matchData.forEach((stardata) => {
console.log(stardata);
});
}
},
{
"name": "Mike",
"age": 40,
"type": "boxer",
"matchData": [
{ "played": 5, "win": 3, "lose": 2, "available": "NO" }
],
"starsData": function() {
this.matchData.forEach((stardata) => {
console.log(stardata);
});
}
}
];
superStars.forEach(superStar => {
console.log(
Details for ${superStar.name}:
);superStar.starsData();
});