-2

I'm trying do some validations based of an object with key-value pairs like below

var map = {'1': ['a','b','c'], '2': ['d','e'], '3': 'f'}

and I want to check if my desired value is in a particular key segment if('a' in map[1])

is there a way where we can check it like above?

  • 2
    [`in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) checks if a key exists. [`Array#includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) checks an array for a value. – Nina Scholz Jul 10 '19 at 17:18
  • `object.hasOwnProperty( 'value_to_check_for' )` is also useful – admcfajn Jul 10 '19 at 17:19
  • @depperm it still won't work though because it's not the same object. –  Jul 10 '19 at 17:26
  • 1
    Googling for your question title, the top two results are stackoverflow questions that answer this. –  Jul 10 '19 at 17:27

2 Answers2

2

You could use Array#includes for an array and check if an item exists.

var map = { 1: ['a','b','c'], 2: ['d','e'], 3: 'f' };

if (map[1].includes('a')) console.log('yes!');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I tried it already but its not letting me use includes as map[1] is returning an object in m y case instead of an array. I checked it with 'typepf(map[]1])' and it is returning an object – Sindhoor Preetham Jul 10 '19 at 17:40
1

You can use indexOf

var map = {'1': ['a','b','c'], '2': ['d','e'], '3': 'f'}

console.log(map['1'].indexOf('a')>-1)
console.log(map['2'].indexOf('a')>-1)
console.log(map['3'].indexOf('f')>-1)
depperm
  • 10,606
  • 4
  • 43
  • 67