0
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'

3
  • 1
    the output is form of array ? Commented May 4, 2022 at 5:59
  • 1
    'second': 205, shouldn't this be an array? Commented May 4, 2022 at 6:01
  • yes, output should be an array Commented May 4, 2022 at 8:53

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.