Home > Software design >  Get the key of a JS Object from the value
Get the key of a JS Object from the value

Time:05-20

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?

CodePudding user response:

@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;
                }
            }
        )
        break;

    }
    return output
}

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Simple,

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

function getKeyByValue(object, value) {
 for (const key in object) {
   if (Object.hasOwnProperty.call(object, key)) {
     for (let i = 0; i < object[key].length; i  ) {
      if (object[key][i] === value) {
        return key;
        
      }
    }
     
   }
 }
}
console.log(getKeyByValue(exampleObject,'test3'))
  • Related