如何通过其值将某些键查找到混合对象数组中?

how to find certain key by its value into mixed objects array?

const items = [ { 'first': [205, 208, 222] }, { 'second': 205 } ]

我需要在 value/values

中巧合地找到钥匙

示例:

通过id=205找到key,输出:'first', 'second'

通过id=208找到key,输出:'first'

您可以尝试获取键和值的数组,然后 filter 键并检查 values 中对应的索引是否包含变量 id.

const items = [ { 'first': [205, 208, 222] }, { 'second': 205 } ]
const id = 205;
let keys = items.map(item => Object.keys(item)[0]);
let values = items.map(item => Object.values(item)[0]);

let output = keys.filter((_, index) => (values[index] == id || (typeof(values[index]) == 'object' && values[index].includes(id))));
console.log(output)

您可以单击 'Run code snippet' 并查看问题中提到的输出

const items = [{
    first: [205, 208, 222],
  },
  {
    second: 205,
  },
];

const toFind = 205;

const fin = items.reduce((finalOutput, item) => {
  let key = Object.keys(item)[0];
  if (Array.isArray(item[key])) {
    if (item[key].includes(toFind)) finalOutput.push(key);
  } else if (item[key] === toFind) {
    finalOutput.push(key);
  }
  return finalOutput;
}, []);

console.log(fin);

你可以这样做

const items = [ { 'first': [205, 208, 222] }, { 'second': 205 } ]


const findKey = (data, value) => data.reduce((res, item) => {
  let [[key, v]] = Object.entries(item)
  v = Array.isArray(v)?v: [v]
  if(v.includes(value)){
    return [...res, key]
  }
  return res
}, [])

console.log(findKey(items, 205))
console.log(findKey(items, 208))

正确格式化您的 items 数据,然后:

const items = [ { 'first': [205, 208, 201] }, { 'second': [205] } ]

const findKeys = n => items.reduce((acc, obj) => 
    Object.values(obj).some(arr => arr.includes(n)) ? 
        acc.concat(Object.keys(obj)) : 
        acc, 
    [])

const res = findKeys(208)

// Output: ['first']
console.log(res)