如何使用键名检索对象中的特定键?

时间:2019-07-08 23:32:53

标签: javascript object

我想使用该值获取对象键名称。有可能吗?

我尝试使用Object.keys,无法想象循环工作成功。

for (var x in inspections) {
    if (inspections[x] == "NA") {
         //Somehow get inspections key at inspections value`
    }
}         

4 个答案:

答案 0 :(得分:1)

只要您不定位IE11,就可以使用Object.entries,对于IE11,您可以相当轻松地创建匀场片。

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

针对您的情况:

for (let [key, value] of Object.entries(inspections)) {
  if (value === 'NA'){
    console.log(key);
  }
}

答案 1 :(得分:1)

const getKey = (obj, val) => Object.getOwnPropertyNames(obj).find(key => obj[key] === val);

const obj = { prop1: 'test1', prop2: 'test2' };

console.log(getKey(obj, 'test2'));

答案 2 :(得分:0)

const inspections = { "1": "NA", "2": "A" }

for (let x in inspections) {
  if (inspections[x] == "NA") {
    console.log(x);
  }
}

您发布的答案实际上是正确的。在if语句中找到匹配项时,x是您想要的键。如果要获取密钥,请执行以下操作:

const inspections = { "1": "NA", "2": "A" }

let key = null;

for (let x in inspections) {
  if (inspections[x] == "NA") {
    key = x;
    break;
  }
}

if (key !== null) {
    // we found a key, do something with it
    console.log(key);
}

答案 3 :(得分:0)

这将为传入的值获取找到的第一个键。

enter image description here