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

Time:05-04

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'

CodePudding user response:

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))

CodePudding user response:

You can try getting the arrays of keys and values, then filter the keys and check if the corresponding index in values contain the variable 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)

CodePudding user response:

You can click on 'Run code snippet' and see the output as mentioned in the question

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);

CodePudding user response:

Format your items data properly, then:

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)
  • Related