我需要找到包含特定字符串的键(类型:数组)。实际数据如下所示
我尝试使用_.invert()反转特定对象。但是没有意义,因为它将整个数组转换为字符串
{
"key1": ['asd','yrt','uyt'],
"key2": ['nbm','inb','oiu']
}
所需的响应是,如果提供了数组元素,我们可以获取key_name。 也就是说,如果输入的是“ asd”,我们需要能够说出密钥是key1
答案 0 :(得分:2)
获取键并找到包含元素的元素。
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);
答案 1 :(得分:1)
您打算多久这样做一次?如果只有一次,则:
data = {
"key1": ['asd','yrt','uyt'],
"key2": ['nbm','inb','oiu']
}
needle = 'oiu'
magicKey = Object.keys(data).filter(key => data[key].includes(needle))
否则,您将要制作一本新字典,将可能的针头用作键!
答案 2 :(得分:1)
const obj = { key1: ['asd','yrt','uyt'], key2: ['nbm','inb','oiu']}
const keyResult = Object.entries(obj).find(element => element[1].includes('asd'))
console.log(keyResult[0] || 'not found')
答案 3 :(得分:0)
它可能看起来像这样:
let elementToFind = "asd";
let object = {
"key1": ['asd','yrt','uyt'],
"key2": ['nbm','inb','oiu']
}
let output;
for(let key in object) { // iterate over every key in object
if(object.hasOwnProperty(key)) { // check if we don't try to access one of object's prototype fields etc.
if(object[key].includes(elementToFind)) {
// check if object[key] which is array, contains element we look for
// if so, break the loop to prevent it from further searching
output = key;
break;
}
}
}
答案 4 :(得分:0)
let search = 'asd'
let obj = {
"key1": ['asd','yrt','uyt'],
"key2": ['nbm','inb','oiu']
}
Object.keys(obj).find(key => obj[key].indexOf(search) > -1)
If there can be multiple such keys use filter instead of find.
答案 5 :(得分:0)
一种方法是迭代从Object.entries
生成的键/值,并返回在值(数组)中找到字符串的键。
const obj = {
key1: ['asd','yrt','uyt'],
key2: ['nbm','inb','oiu']
}
function getKey(obj, str) {
for (let [key, arr] of Object.entries(obj)) {
if (arr.includes(str)) return key;
}
return null;
}
console.log(getKey(obj, 'inb'));
console.log(getKey(obj, 'asd'));
答案 6 :(得分:0)
您可以编写一个递归返回路径的函数...
const hasKey = (key, data) => ({}).hasOwnProperty.call(data, key);
const typeOf = value => ({}).toString.call(value).replace(/\[object (\w+)]/, '$1');
const isLeaf = value => ['String', 'Boolean', 'Null', 'Undefined', 'Number', 'Date', 'Function'].includes(typeOf(value));
const needle = 'asd';
const haystack = {
"key1": ['asd1','yrt','uyt'],
"key2": ['nbm','inb','oiu'],
key3: {
key4: ['asd'],
}
};
const find = (needle, haystack, path = []) => {
if (isLeaf(haystack)) {
return needle === haystack && path;
}
for (let [key, value] of Object.entries(haystack)) {
const result = find(needle, value, path.concat(key));
if (result) { return result; }
}
};
console.log('find', find(needle, haystack));