skip to Main Content

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


  1. let superStars = [{
        "name": "Brock",
        "age": 38,
        "type": "wwe",
        matchData: [
          {
            played: 10,
            win: 9,
            lose: 1,
            available: "YES"
          },
           {
            played: 5,
            win: 3,
            lose: 2,
            available: "NO"
          }
        ],
        "name": "mike",
        "age": 40,
        "type": "boxer",
        starsData: function () {
          this.matchData.forEach((stardata) => {
            console.log(stardata);
          });
        }
      }];
    superStars[0].starsData();

    superstars is an array. And the function starsData 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 need matchData once, as shown above.

    Login or Signup to reply.
  2. 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();
    });

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search