Skip to content
Advertisement

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

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

I need to find keys by all coincidence into its value/values

example:

find key by id=205, output: 'first', 'second'

find key by id=208, output: 'first'

Advertisement

Answer

You can do something like this

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))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement