简体   繁体   中英

Get the key of a JS Object from the value

I am trying to get the key of a JS Object in Typescript from an input value, the problem is that the values are inside an Array .

This is what I have seen in the case that the value is not in an array:

const exampleObject = {
  key1: 'Geeks',
  key2: 'Javascript'
};

function getKeyByValue(object, value) {
  for (var prop in object) {
      if (object.hasOwnProperty(prop)) {
          if (object[prop] === value)
          return prop;
      }
  }
}

console.log(getKeyByValue(exampleObject,'Geeks')) // key1

This is an example of my object that I want to get the key from:

const exampleObject = {
  key1: ['Geeks','test1','test2'],
  key2: ['Javascript','test3','test4']
};

function getKeyByValue(object, value) {
  for (var prop in object) {
      if (object.hasOwnProperty(prop)) {
          if (object[prop] === value)
          return prop;
      }
  }
}

console.log(getKeyByValue(exampleObject,'Geeks')) // undefined

I need to get the key without using Array.prototype.includes() , because typing the resulting variable as String gives me an error that it may be undefined.

My problem : I don't know how to go through the array inside the function to find the value and get the key

Update :

What I want is to avoid the possibility of returning an undefined, since the input value will always be inside the object, how can I achieve this?

@segmet You can use my code

const exampleObject = {
    key1: ['Geeks', 'test1', 'test2'],
    key2: ['Javascript', 'test3', 'test4']
};

function getKeyByValue(object, value) {
    var output = "";
    for (var prop in object) {
    // finding and removing element from array
        object[prop].find(i => {
                if (i === value) {
                    output = prop;
                    return prop;
                }
            }
        )
    }
    return output
}

console.log(getKeyByValue(exampleObject, 'Geeks'))
function getKeyByValue(object, value) {
  const key = Object.entries(object).filter(([key, val]) => val.includes(value));
  return Object.fromEntries(key);
}

Try this function instead You will get the object matching your keys

You can do something like this and then check for null


const getKeyFromValue = (obj:Object, value:string | string[]) => { 
    for (let key in obj) {
        if (typeof value === 'string') {
            if (obj[ key ].includes(value)) {
                return key;
            }
        }
        else if (Array.isArray(value)) { 
            if (obj[ key ].every(val => value.includes(val))) {
                return key;
            }
        }
       
    }
    return null;
}

One more try:

 const exampleObject = { key1: ['Geeks','test1','test2'], key2: ['Javascript','test3','test4'] }; function getKeyByValue(obj, data) { for (const [key, value] of Object.entries(obj)) { return (~value.indexOf(data)) ? key : false } } console.log(getKeyByValue(exampleObject,'Geeks'))

You can achieve this with a single line of code by using 3 JavaScript methods - Object.keys() , Array.find() & Array.indexOf() :

 const exampleObject = { key1: ['Geeks','test1','test2'], key2: ['Javascript','test3','test4'] }; function getKeyByValue(object, value) { const res = Object.keys(exampleObject).find(key => exampleObject[key].indexOf(value) !== -1); return res || '' } console.log(getKeyByValue(exampleObject,'Geeks'))

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