-1

I have an array containing the following data.

[ { name: 'hello', value: 'Bot hello!' },
  { name: 'help', value: 'Print help sheet.' },
  { name: 'kick', value: 'Kicks a user.' },
  { name: 'ping', value: 'Check the bot\'s Connection' },
  { name: 'roll', value: 'Roll a die.' } ]

var str = "ping"
if (str == //One of the names in the array){
   //Do stuff

}

How can I create a function to check whether a string such as "ping" is equal to one of the values in the "name:" category? I want this to be dynamic so if the string is equal to "roll" it will flag that roll is in the array.

j08691
  • 204,283
  • 31
  • 260
  • 272
Nhoward292
  • 11
  • 6

2 Answers2

1

In ES6:

var data = [ { name: 'hello', value: 'Bot hello!' },
  { name: 'help', value: 'Print help sheet.' },
  { name: 'kick', value: 'Kicks a user.' },
  { name: 'ping', value: 'Check the bot\'s Connection' },
  { name: 'roll', value: 'Roll a die.' } ]
  
var str = "ping"

console.log(data.some(x => x.name === str))
CRice
  • 29,968
  • 4
  • 57
  • 70
0

You could use native array method some

function contain(array, value) {
  return array.some(a => a.name === value);
}
if (contain(array, 'ping')){
   //Do stuff

}
Piotr Białek
  • 2,569
  • 1
  • 17
  • 26