Search code examples
javascriptarraysjavascript-objects

how to change the elements inside an object which is inside an array using forEach loop


how do i create a forEach loop for the elements inside the object which is inside an array?

const array = [
  {
    username: "john",
    team: "red",
    score: 5,
    items: ["ball", "book", "pen"]
  },
  {
    username: "becky",
    team: "blue",
    score: 10,
    items: ["tape", "backpack", "pen"]
  },
  {
    username: "susy",
    team: "red",
    score: 55,
    items: ["ball", "eraser", "pen"]
  },
  {
    username: "tyson",
    team: "green",
    score: 1,
    items: ["book", "pen"]
  },

];

i have to add an ! for each username


Solution

  • As this is a multidimensional array, you have to call the index for username in order to add the ! sign

    const array = [
      {
        username: "john",
        team: "red",
        score: 5,
        items: ["ball", "book", "pen"]
      },
      {
        username: "becky",
        team: "blue",
        score: 10,
        items: ["tape", "backpack", "pen"]
      },
      {
        username: "susy",
        team: "red",
        score: 55,
        items: ["ball", "eraser", "pen"]
      },
      {
        username: "tyson",
        team: "green",
        score: 1,
        items: ["book", "pen"]
      },
    
    ];
    
    array.forEach(element => console.log("!"+element["username"]));