简体   繁体   English

从 value 中获取 JS Object 的 key

[英]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 .我试图从输入值中获取 Typescript 中JS Objectkey ,问题是这些值在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.我需要在不使用Array.prototype.includes()的情况下获取密钥,因为将结果变量键入为String会给我一个error ,即它可能未定义。

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 @segmet 你可以使用我的代码

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你可以做这样的事情,然后检查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() :您可以通过使用 3 个 JavaScript 方法 - 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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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