Search code examples
javascriptarraysecmascript-6foreachjavascript-objects

How can I find a special character like '!' or '?' in an objects array in JavaScript?


I wanted to find the usernames with '!' and '?' in an objects array and store them in a new array.

The objects array is as follows.

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 tried the test() method with forEach looping, but I couldn't get the preferred output. How can I do it? Can I use map() instead of forEach to iterate through objects?


Solution

  • Specific to your use case this is how you would get all the usernames that contain those characters.

    Array.filter creates a new array so you dont have to mutate the original one to get the values you want.

    array.filter(obj => obj.username.includes("!") || obj.username.includes("?"))