This is an array and I want to use foreach to create an array using forEach that has all the usernames with a “!” to each of the usernames
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"] }, ];
What i try in JS:
const double=[]; const newArray = array.forEach(array[i].username)=>{ double.push(array[i].username+"!"); }); console.log(double);
What i got in error:
Uncaught SyntaxError: Unexpected token .
What is the right way to use foreach to access the object in the array?
Advertisement
Answer
You can do it with forEach
like so (note using var
not const
because you can’t modify const
):
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"] }, ]; var double = []; array.forEach(person => double.push(person.username + "!")); console.log(double);
However, it’s much simpler to use map
:
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"] }, ]; var double = array.map(person => person.username + "!"); console.log(double);