简体   繁体   中英

How to retrieve the key from an array of values of a JSON object?

Let there is an object which has values as arrays. For example,

    const obj = {
      'abc': ['xyz','tuv'],
      'def': ['qrs']
    }

How can we get the key of 'tuv' from the object?

This is different from this question, where the value was not an array. How to get a key in a JavaScript object by its value?

You could get the keys and filter by checking the values.

 const getKeys = (object, value) => Object.keys(object).filter(k => object[k].includes(value)), obj = { abc: ['xyz','tuv'], def: ['qrs'] }; console.log(getKeys(obj, 'tuv'));

I am assuming one value will not have multiple keys.

const getKeyByValue = (object, value) => Object.keys(object)
  .map(key => object[key].map(val => { if (val === value) { return key }}))
  .flat().filter(key => key)[0] || false

So, if we want to get the key of 'tuv', we can call this method like this,

getKeyByValue(obj, 'tuv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM