首页 > 解决方案 > Find the key in an object which contains a particular value in an array

问题描述

I need to find the key(type:array) which contains a specific string. The actual data would look like as provided below

I tried to inverse the particular object with _.invert(). But doesnt make sense as it would convert the entire array to a string

{
  "key1": ['asd','yrt','uyt'],
  "key2": ['nbm','inb','oiu']
}

The response desired is that with we can fetch the key_name if an array element is provided. ie if the input is lets 'asd' we need to be able to say that the key was key1

标签: javascript

解决方案


拿钥匙并找到包含的元素。

const
    find = (object, value) => Object.keys(object).find(k => object[k].includes(value)),
    object = { key1: ['asd','yrt','uyt'], key2: ['nbm','inb','oiu'] },
    key = find(object, 'asd');
    
console.log(key);


推荐阅读