-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.

3
  • You can use Array#some like this: if(arr.some(o => o.name === str)) { ... }. Commented Dec 4, 2017 at 21:09
  • Please try searching before asking Commented Dec 4, 2017 at 21:11
  • Sorry. I tried searching however I couldn't find anything for using sub arrays. Anyway the example provided in the one you linked works. Thanks Commented Dec 4, 2017 at 21:28

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this works :) Thanks dude
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

}

5 Comments

Why use find and not use its return value (properly). Use some for checking, and find for actual finding.
This was returning an error saying that the { in the if statement wasn't valid.
@nathanial292 updated, i forgot one ")".
Do you know how to then get the matching value in the array. Where the string matches the name?
array.find(a => a.name === value);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.